<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>企业管理系统</title>
    <!-- Vue 3 -->
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <!-- Axios -->
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <!-- Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- Font Awesome -->
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <!-- Chart.js -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.8/dist/chart.umd.min.js"></script>
    
    <!-- 配置 Tailwind CSS -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#4F46E5',
                        secondary: '#6366F1',
                        success: '#10B981',
                        warning: '#F59E0B',
                        danger: '#EF4444',
                        info: '#3B82F6',
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                },
            }
        }
    </script>
    
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .sidebar-item {
                @apply flex items-center px-4 py-3 text-gray-700 hover:bg-primary/10 hover:text-primary rounded-lg transition-all duration-200 cursor-pointer;
            }
            .sidebar-item.active {
                @apply bg-primary/20 text-primary font-medium;
            }
            .card-hover {
                @apply hover:shadow-lg transition-all duration-300 transform hover:-translate-y-1;
            }
            .table-header {
                @apply bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider;
            }
            .table-cell {
                @apply whitespace-nowrap px-4 py-3 text-sm text-gray-700;
            }
            .btn {
                @apply px-4 py-2 rounded-md font-medium transition-all duration-200;
            }
            .btn-primary {
                @apply bg-primary text-white hover:bg-primary/90;
            }
            .btn-secondary {
                @apply bg-gray-200 text-gray-800 hover:bg-gray-300;
            }
            .input-field {
                @apply w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary;
            }
            .progress-bar {
                @apply h-2 bg-gray-200 rounded-full overflow-hidden;
            }
            .progress-fill {
                @apply h-full rounded-full transition-all duration-500 ease-in-out;
            }
        }
    </style>
    
    <style>
        /* 仪表盘卡片动画 */
        .dashboard-card {
            animation: fadeIn 0.5s ease-out;
        }
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        /* 进度条颜色 */
        .progress-fill.low {
            background-color: #F59E0B; /* 警告色 */
        }
        .progress-fill.medium {
            background-color: #3B82F6; /* 信息色 */
        }
        .progress-fill.high {
            background-color: #10B981; /* 成功色 */
        }
        
        /* 刷新按钮动画 */
        .refresh-btn:hover {
            animation: spin 1s linear;
        }
        @keyframes spin {
            from { transform: rotate(0deg); }
            to { transform: rotate(360deg); }
        }
        
        /* 时间线样式 */
        .timeline-item::before {
            content: '';
            position: absolute;
            left: -16px;
            top: 6px;
            width: 10px;
            height: 10px;
            border-radius: 50%;
            background-color: #4F46E5;
        }
        
        .timeline-item:not(:last-child)::after {
            content: '';
            position: absolute;
            left: -12px;
            top: 22px;
            bottom: 0;
            width: 2px;
            background-color: #E5E7EB;
        }
        
        /* 模态框动画 */
        .modal-transition-enter-active, .modal-transition-leave-active {
            transition: opacity 0.3s ease;
        }
        .modal-transition-enter-from, .modal-transition-leave-to {
            opacity: 0;
        }
        
        .modal-content-enter-active, .modal-content-enter-leave {
            transition: transform 0.3s ease;
        }
        .modal-content-enter-from {
            transform: scale(0.9);
        }
        .modal-content-enter-leave-to {
            transform: scale(0.9);
        }
    </style>
</head>
<body class="bg-gray-50 min-h-screen">
    <div id="app">
        <!-- 登录页面 -->
        <div v-if="!isLoggedIn" class="flex items-center justify-center min-h-screen bg-gray-50">
            <div class="w-full max-w-md">
                <!-- 登录表单 -->
                <div v-if="authView === 'login'" class="bg-white p-8 rounded-lg shadow-lg">
                    <div class="text-center mb-8">
                        <h1 class="text-3xl font-bold text-gray-900">企业管理系统</h1>
                        <p class="text-gray-500 mt-2">请登录以继续</p>
                    </div>
                    
                    <div v-if="loginError" class="bg-red-100 text-red-700 px-4 py-3 rounded mb-4">
                        {{ loginError }}
                    </div>
                    
                    <form @submit.prevent="login" class="space-y-4">
                        <div>
                            <label for="username" class="block text-sm font-medium text-gray-700 mb-1">用户名</label>
                            <input type="text" id="username" v-model="username" class="input-field" placeholder="请输入用户名" required>
                        </div>
                        
                        <div>
                            <label for="password" class="block text-sm font-medium text-gray-700 mb-1">密码</label>
                            <input type="password" id="password" v-model="password" class="input-field" placeholder="请输入密码" required>
                        </div>
                        
                        <button type="submit" class="w-full btn btn-primary">
                            <i class="fa fa-sign-in mr-2"></i>登录
                        </button>
                    </form>
                    
                    <div class="text-center text-sm text-gray-500 mt-4 space-y-2">
                        <a href="#" class="text-primary hover:underline" @click.prevent="authView = 'register'">
                            没有账号？立即注册
                        </a>
                        <br>
                        <a href="#" class="text-primary hover:underline" @click.prevent="authView = 'forgot'">
                            忘记密码？
                        </a>
                    </div>
                    
                    <div class="text-center text-sm text-gray-500 mt-6">
                        <p>测试账号：admin / 123456</p>
                    </div>
                </div>

                <!-- 注册表单 -->
                <div v-if="authView === 'register'" class="bg-white p-8 rounded-lg shadow-lg">
                    <div class="text-center mb-8">
                        <h1 class="text-3xl font-bold text-gray-900">用户注册</h1>
                        <p class="text-gray-500 mt-2">创建新账号</p>
                    </div>
                    
                    <div v-if="registerError" class="bg-red-100 text-red-700 px-4 py-3 rounded mb-4">
                        {{ registerError }}
                    </div>
                    
                    <div v-if="registerSuccess" class="bg-green-100 text-green-700 px-4 py-3 rounded mb-4">
                        {{ registerSuccess }}
                    </div>
                    
                    <form @submit.prevent="register" class="space-y-4">
                        <div>
                            <label for="reg-username" class="block text-sm font-medium text-gray-700 mb-1">用户名</label>
                            <input type="text" id="reg-username" v-model="registerForm.username" class="input-field" placeholder="请输入用户名" required>
                        </div>
                        
                        <div>
                            <label for="reg-email" class="block text-sm font-medium text-gray-700 mb-1">邮箱</label>
                            <input type="email" id="reg-email" v-model="registerForm.email" class="input-field" placeholder="请输入邮箱" required>
                        </div>
                        
                        <div>
                            <label for="reg-fullname" class="block text-sm font-medium text-gray-700 mb-1">姓名</label>
                            <input type="text" id="reg-fullname" v-model="registerForm.full_name" class="input-field" placeholder="请输入姓名" required>
                        </div>
                        
                        <div>
                            <label for="reg-password" class="block text-sm font-medium text-gray-700 mb-1">密码</label>
                            <input type="password" id="reg-password" v-model="registerForm.password" class="input-field" placeholder="请输入密码（至少6位）" required>
                        </div>
                        
                        <div>
                            <label for="reg-confirm-password" class="block text-sm font-medium text-gray-700 mb-1">确认密码</label>
                            <input type="password" id="reg-confirm-password" v-model="registerForm.confirmPassword" class="input-field" placeholder="请再次输入密码" required>
                        </div>
                        
                        <button type="submit" class="w-full btn btn-primary" :disabled="isRegistering">
                            <i class="fa fa-user-plus mr-2"></i>
                            {{ isRegistering ? '注册中...' : '注册' }}
                        </button>
                    </form>
                    
                    <div class="text-center text-sm text-gray-500 mt-4">
                        <a href="#" class="text-primary hover:underline" @click.prevent="authView = 'login'">
                            已有账号？立即登录
                        </a>
                    </div>
                </div>

                <!-- 忘记密码表单 -->
                <div v-if="authView === 'forgot'" class="bg-white p-8 rounded-lg shadow-lg">
                    <div class="text-center mb-8">
                        <h1 class="text-3xl font-bold text-gray-900">忘记密码</h1>
                        <p class="text-gray-500 mt-2">重置您的密码</p>
                    </div>
                    
                    <div v-if="forgotError" class="bg-red-100 text-red-700 px-4 py-3 rounded mb-4">
                        {{ forgotError }}
                    </div>
                    
                    <div v-if="forgotSuccess" class="bg-green-100 text-green-700 px-4 py-3 rounded mb-4">
                        {{ forgotSuccess }}
                    </div>
                    
                    <div v-if="resetToken" class="bg-blue-100 text-blue-700 px-4 py-3 rounded mb-4">
                        <strong>重置令牌：</strong>{{ resetToken }}
                        <br><small class="text-xs">（实际环境会通过邮件发送）</small>
                    </div>
                    
                    <form @submit.prevent="forgotPassword" class="space-y-4">
                        <div>
                            <label for="forgot-email" class="block text-sm font-medium text-gray-700 mb-1">邮箱</label>
                            <input type="email" id="forgot-email" v-model="forgotForm.email" class="input-field" placeholder="请输入注册时的邮箱" required>
                        </div>
                        
                        <button type="submit" class="w-full btn btn-primary" :disabled="isSendingReset">
                            <i class="fa fa-envelope mr-2"></i>
                            {{ isSendingReset ? '发送中...' : '发送重置链接' }}
                        </button>
                    </form>
                    
                    <div v-if="resetToken" class="mt-4">
                        <h3 class="text-lg font-medium text-gray-900 mb-2">重置密码</h3>
                        <form @submit.prevent="resetPassword" class="space-y-4">
                            <div>
                                <label for="reset-password" class="block text-sm font-medium text-gray-700 mb-1">新密码</label>
                                <input type="password" id="reset-password" v-model="resetForm.new_password" class="input-field" placeholder="请输入新密码" required>
                            </div>
                            
                            <div>
                                <label for="reset-confirm-password" class="block text-sm font-medium text-gray-700 mb-1">确认新密码</label>
                                <input type="password" id="reset-confirm-password" v-model="resetForm.confirm_password" class="input-field" placeholder="请再次输入新密码" required>
                            </div>
                            
                            <button type="submit" class="w-full btn btn-primary" :disabled="isResetting">
                                <i class="fa fa-key mr-2"></i>
                                {{ isResetting ? '重置中...' : '重置密码' }}
                            </button>
                        </form>
                    </div>
                    
                    <div class="text-center text-sm text-gray-500 mt-4">
                        <a href="#" class="text-primary hover:underline" @click.prevent="authView = 'login'">
                            返回登录
                        </a>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 主应用页面 -->
        <div v-else class="flex h-screen overflow-hidden">
            <!-- 侧边栏 -->
            <aside class="w-64 bg-white shadow-md flex flex-col">
                <div class="p-4 border-b">
                    <h2 class="text-xl font-bold text-primary flex items-center">
                        <i class="fa fa-building-o mr-2"></i>企业管理系统
                    </h2>
                </div>
                
                <nav class="flex-1 p-4 space-y-1">
                    <div class="sidebar-item" :class="{ active: currentView === 'dashboard' }" @click="currentView = 'dashboard'">
                        <i class="fa fa-tachometer w-6"></i>
                        <span class="ml-2">仪表盘</span>
                    </div>
                    <div v-if="currentUser?.is_superuser" class="sidebar-item" :class="{ active: currentView === 'users' }" @click="currentView = 'users'">
                        <i class="fa fa-users w-6"></i>
                        <span class="ml-2">用户管理</span>
                    </div>
                    <div v-if="currentUser?.is_superuser" class="sidebar-item" :class="{ active: currentView === 'departments' }" @click="currentView = 'departments'">
                        <i class="fa fa-sitemap w-6"></i>
                        <span class="ml-2">部门管理</span>
                    </div>
                    <div v-if="currentUser?.is_superuser" class="sidebar-item" :class="{ active: currentView === 'projects' }" @click="currentView = 'projects'">
                        <i class="fa fa-tasks w-6"></i>
                        <span class="ml-2">项目管理</span>
                    </div>
                    <div class="sidebar-item" :class="{ active: currentView === 'attendance' }" @click="currentView = 'attendance'">
                        <i class="fa fa-calendar-check-o w-6"></i>
                        <span class="ml-2">考勤管理</span>
                    </div>
                </nav>
                
                <div class="p-4 border-t">
                    <div class="flex items-center justify-between">
                        <div class="flex items-center">
                            <div class="w-8 h-8 bg-primary/10 rounded-full flex items-center justify-center text-primary">
                                <i class="fa fa-user"></i>
                            </div>
                            <span class="ml-2 text-gray-700">{{ username }}</span>
                        </div>
                        <button class="text-gray-500 hover:text-primary" @click="logout">
                            <i class="fa fa-sign-out"></i>
                        </button>
                    </div>
                </div>
            </aside>
            
            <!-- 主内容区域 -->
            <main class="flex-1 overflow-y-auto bg-gray-50 p-6">
                <!-- 仪表盘视图 -->
                <div v-if="currentView === 'dashboard'">
                    <div class="flex items-center justify-between mb-6">
                        <h1 class="text-2xl font-bold text-gray-900">仪表盘</h1>
                        <div class="flex items-center space-x-4">
                            <span class="text-gray-600">{{ formatDate(new Date()) }}</span>
                            <button class="p-2 bg-white rounded-full shadow-sm text-gray-600 hover:text-primary refresh-btn" @click="refreshData">
                                <i class="fa fa-refresh"></i>
                            </button>
                        </div>
                    </div>
                    
                    <!-- 统计卡片 -->
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-6">
                        <div class="bg-white rounded-lg shadow-sm p-6 dashboard-card card-hover">
                            <div class="flex items-center justify-between">
                                <div>
                                    <p class="text-gray-500 text-sm">用户总数</p>
                                    <h3 class="text-2xl font-bold text-gray-900 mt-1">{{ users.length }}</h3>
                                    <p class="text-success text-xs mt-2">
                                        <i class="fa fa-arrow-up mr-1"></i>
                                        {{ getPercentageChange(10, users.length) }}% 较上月
                                    </p>
                                </div>
                                <div class="w-12 h-12 bg-blue-100 rounded-full flex items-center justify-center text-blue-500">
                                    <i class="fa fa-users text-xl"></i>
                                </div>
                            </div>
                        </div>
                        
                        <div class="bg-white rounded-lg shadow-sm p-6 dashboard-card card-hover" style="animation-delay: 0.1s;">
                            <div class="flex items-center justify-between">
                                <div>
                                    <p class="text-gray-500 text-sm">部门总数</p>
                                    <h3 class="text-2xl font-bold text-gray-900 mt-1">{{ departments.length }}</h3>
                                    <p class="text-success text-xs mt-2">
                                        <i class="fa fa-arrow-up mr-1"></i>
                                        {{ getPercentageChange(4, departments.length) }}% 较上月
                                    </p>
                                </div>
                                <div class="w-12 h-12 bg-green-100 rounded-full flex items-center justify-center text-green-500">
                                    <i class="fa fa-sitemap text-xl"></i>
                                </div>
                            </div>
                        </div>
                        
                        <div class="bg-white rounded-lg shadow-sm p-6 dashboard-card card-hover" style="animation-delay: 0.2s;">
                            <div class="flex items-center justify-between">
                                <div>
                                    <p class="text-gray-500 text-sm">活跃项目</p>
                                    <h3 class="text-2xl font-bold text-gray-900 mt-1">{{ activeProjects }}</h3>
                                    <p class="text-success text-xs mt-2">
                                        <i class="fa fa-arrow-up mr-1"></i>
                                        {{ getPercentageChange(6, activeProjects) }}% 较上月
                                    </p>
                                </div>
                                <div class="w-12 h-12 bg-purple-100 rounded-full flex items-center justify-center text-purple-500">
                                    <i class="fa fa-tasks text-xl"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 图表区域 -->
                    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
                        <div class="bg-white rounded-lg shadow-sm p-6">
                            <h3 class="text-lg font-medium text-gray-900 mb-4">项目进度</h3>
                            <div class="h-64">
                                <canvas ref="projectChart"></canvas>
                            </div>
                        </div>
                        
                        <div class="bg-white rounded-lg shadow-sm p-6">
                            <h3 class="text-lg font-medium text-gray-900 mb-4">部门人员分布</h3>
                            <div class="h-64">
                                <canvas ref="departmentChart"></canvas>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 最近项目和活动 -->
                    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
                        <div class="bg-white rounded-lg shadow-sm p-6">
                            <h3 class="text-lg font-medium text-gray-900 mb-4">最近项目</h3>
                            <div v-if="projects.length > 0" class="space-y-4">
                                <div v-for="project in getRecentProjects()" :key="project.id" class="p-3 border border-gray-100 rounded-lg hover:bg-gray-50 transition-colors">
                                    <div class="flex items-center justify-between">
                                        <h4 class="font-medium text-gray-900">{{ project.name }}</h4>
                                        <span class="text-xs px-2 py-1 rounded-full bg-gray-100 text-gray-600">
                                            {{ project.status === 'planning' ? '规划中' : project.status === 'in_progress' ? '进行中' : '已完成' }}
                                        </span>
                                    </div>
                                    <div class="mt-2">
                                        <div class="flex justify-between text-xs text-gray-500 mb-1">
                                            <span>进度</span>
                                            <span>{{ project.progress }}%</span>
                                        </div>
                                        <div class="progress-bar">
                                            <div class="progress-fill" 
                                                 :class="{ low: project.progress < 40, medium: project.progress >= 40 && project.progress < 80, high: project.progress >= 80 }"
                                                 :style="{ width: project.progress + '%' }"></div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div v-else class="text-center py-8 text-gray-500">
                                <i class="fa fa-folder-open-o text-4xl mb-2"></i>
                                <p>暂无项目数据</p>
                            </div>
                        </div>
                        
                        <div class="bg-white rounded-lg shadow-sm p-6">
                            <h3 class="text-lg font-medium text-gray-900 mb-4">最近活动</h3>
                            <div v-if="getRecentActivities().length > 0" class="space-y-4">
                                <div v-for="activity in getRecentActivities().slice(0, 5)" :key="activity.id" class="relative pl-8 timeline-item">
                                    <div>
                                        <p class="text-sm text-gray-700">{{ activity.user }} <span class="text-gray-500">{{ activity.action }}</span></p>
                                        <p class="text-xs text-gray-400 mt-1">{{ formatDate(activity.time) }}</p>
                                    </div>
                                </div>
                            </div>
                            <div v-else class="text-center py-8 text-gray-500">
                                <i class="fa fa-clock-o text-4xl mb-2"></i>
                                <p>暂无活动记录</p>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 用户管理视图 -->
                <div v-else-if="currentView === 'users'">
                    <div class="flex items-center justify-between mb-6">
                        <h1 class="text-2xl font-bold text-gray-900">用户管理</h1>
                        <button class="btn btn-primary" @click="showAddUser = true">
                            <i class="fa fa-plus mr-2"></i>添加用户
                        </button>
                    </div>
                    
                    <div class="bg-white rounded-lg shadow-sm overflow-hidden">
                        <div v-if="users.length > 0" class="overflow-x-auto">
                            <table class="min-w-full divide-y divide-gray-200">
                                <thead class="table-header">
                                    <tr>
                                        <th scope="col" class="px-6 py-3">姓名</th>
                                        <th scope="col" class="px-6 py-3">邮箱</th>
                                        <th scope="col" class="px-6 py-3">部门</th>
                                        <th scope="col" class="px-6 py-3">职位</th>
                                        <th scope="col" class="px-6 py-3">创建日期</th>
                                        <th scope="col" class="px-6 py-3">操作</th>
                                    </tr>
                                </thead>
                                <tbody class="bg-white divide-y divide-gray-200">
                                    <tr v-for="user in users" :key="user.id" class="hover:bg-gray-50 transition-colors">
                                        <td class="table-cell">
                                            <div class="flex items-center">
                                                <div class="w-8 h-8 bg-primary/10 rounded-full flex items-center justify-center text-primary text-sm font-medium mr-2">
                                                    {{ user.full_name.charAt(0) }}
                                                </div>
                                                {{ user.full_name }}
                                            </div>
                                        </td>
                                        <td class="table-cell">{{ user.email }}</td>
                                        <td class="table-cell">
                                            <span class="text-sm text-gray-700">
                                                {{ departments.find(d => d.id === user.department_id)?.name || '未分配' }}
                                            </span>
                                        </td>
                                        <td class="table-cell">{{ user.position }}</td>
                                        <td class="table-cell">{{ user.created_at }}</td>
                                        <td class="table-cell">
                                            <div class="flex space-x-2">
                                                <button class="text-blue-500 hover:text-blue-700" @click="editUser(user.id)">
                                                    <i class="fa fa-pencil"></i>
                                                </button>
                                                <button class="text-red-500 hover:text-red-700" @click="deleteUser(user.id)">
                                                    <i class="fa fa-trash"></i>
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                        <div v-else class="text-center py-12 text-gray-500">
                            <i class="fa fa-users text-4xl mb-2"></i>
                            <p>暂无用户数据</p>
                        </div>
                    </div>
                </div>
                
                <!-- 部门管理视图 -->
                <div v-else-if="currentView === 'departments'">
                    <div class="flex items-center justify-between mb-6">
                        <h1 class="text-2xl font-bold text-gray-900">部门管理</h1>
                        <button class="btn btn-primary" @click="showAddDepartment = true">
                            <i class="fa fa-plus mr-2"></i>添加部门
                        </button>
                    </div>
                    
                    <div class="bg-white rounded-lg shadow-sm overflow-hidden">
                        <div v-if="departments.length > 0" class="overflow-x-auto">
                            <table class="min-w-full divide-y divide-gray-200">
                                <thead class="table-header">
                                    <tr>
                                        <th scope="col" class="px-6 py-3">部门名称</th>
                                        <th scope="col" class="px-6 py-3">描述</th>
                                        <th scope="col" class="px-6 py-3">负责人</th>
                                        <th scope="col" class="px-6 py-3">员工数量</th>
                                        <th scope="col" class="px-6 py-3">创建日期</th>
                                        <th scope="col" class="px-6 py-3">操作</th>
                                    </tr>
                                </thead>
                                <tbody class="bg-white divide-y divide-gray-200">
                                    <tr v-for="department in departments" :key="department.id" class="hover:bg-gray-50 transition-colors">
                                        <td class="table-cell font-medium">{{ department.name }}</td>
                                        <td class="table-cell">{{ department.description }}</td>
                                        <td class="table-cell">
                                            <span class="text-sm text-gray-700">
                                                {{ users.find(u => u.id === department.manager_id)?.full_name || '未设置' }}
                                            </span>
                                        </td>
                                        <td class="table-cell">
                                            <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                                                {{ department.employee_count || 0 }}
                                            </span>
                                        </td>
                                        <td class="table-cell">{{ department.created_at }}</td>
                                        <td class="table-cell">
                                            <div class="flex space-x-2">
                                                <button class="text-blue-500 hover:text-blue-700" @click="editDepartment(department.id)">
                                                    <i class="fa fa-pencil"></i>
                                                </button>
                                                <button class="text-red-500 hover:text-red-700" @click="deleteDepartment(department.id)">
                                                    <i class="fa fa-trash"></i>
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                        <div v-else class="text-center py-12 text-gray-500">
                            <i class="fa fa-sitemap text-4xl mb-2"></i>
                            <p>暂无部门数据</p>
                        </div>
                    </div>
                </div>
                
                <!-- 项目管理视图 -->
                <div v-else-if="currentView === 'projects'">
                    <div class="flex items-center justify-between mb-6">
                        <h1 class="text-2xl font-bold text-gray-900">项目管理</h1>
                        <button class="btn btn-primary" @click="showAddProject = true">
                            <i class="fa fa-plus mr-2"></i>添加项目
                        </button>
                    </div>
                    
                    <div class="bg-white rounded-lg shadow-sm overflow-hidden">
                        <div v-if="projects.length > 0" class="overflow-x-auto">
                            <table class="min-w-full divide-y divide-gray-200">
                                <thead class="table-header">
                                    <tr>
                                        <th scope="col" class="px-6 py-3">项目名称</th>
                                        <th scope="col" class="px-6 py-3">负责人</th>
                                        <th scope="col" class="px-6 py-3">所属部门</th>
                                        <th scope="col" class="px-6 py-3">预算</th>
                                        <th scope="col" class="px-6 py-3">进度</th>
                                        <th scope="col" class="px-6 py-3">状态</th>
                                        <th scope="col" class="px-6 py-3">操作</th>
                                    </tr>
                                </thead>
                                <tbody class="bg-white divide-y divide-gray-200">
                                    <tr v-for="project in projects" :key="project.id" class="hover:bg-gray-50 transition-colors">
                                        <td class="table-cell font-medium">{{ project.name }}</td>
                                        <td class="table-cell">{{ project.manager_name }}</td>
                                        <td class="table-cell">
                                            <span class="text-sm text-gray-700">
                                                {{ departments.find(d => d.id === project.department_id)?.name || '未分配' }}
                                            </span>
                                        </td>
                                        <td class="table-cell">¥{{ project.budget.toLocaleString() }}</td>
                                        <td class="table-cell">
                                            <div class="flex items-center">
                                                <div class="w-32 h-2 bg-gray-200 rounded-full overflow-hidden mr-2">
                                                    <div class="progress-fill" 
                                                         :class="{ low: project.progress < 40, medium: project.progress >= 40 && project.progress < 80, high: project.progress >= 80 }"
                                                         :style="{ width: project.progress + '%' }"></div>
                                                </div>
                                                <span class="text-sm text-gray-600">{{ project.progress }}%</span>
                                            </div>
                                        </td>
                                        <td class="table-cell">
                                            <span v-if="project.status === 'planning'" class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800">
                                                <i class="fa fa-clock-o mr-1"></i>规划中
                                            </span>
                                            <span v-else-if="project.status === 'in_progress'" class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                                                <i class="fa fa-cog fa-spin mr-1"></i>进行中
                                            </span>
                                            <span v-else class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
                                                <i class="fa fa-check mr-1"></i>已完成
                                            </span>
                                        </td>
                                        <td class="table-cell">
                                            <div class="flex space-x-2">
                                                <button class="text-blue-500 hover:text-blue-700" @click="editProject(project.id)">
                                                    <i class="fa fa-pencil"></i>
                                                </button>
                                                <button class="text-red-500 hover:text-red-700" @click="deleteProject(project.id)">
                                                    <i class="fa fa-trash"></i>
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                        <div v-else class="text-center py-12 text-gray-500">
                            <i class="fa fa-tasks text-4xl mb-2"></i>
                            <p>暂无项目数据</p>
                        </div>
                    </div>
                </div>
                <!-- 考勤管理视图 -->
                <div v-if="currentView === 'attendance'">
                    <div class="flex items-center justify-between mb-6">
                        <h1 class="text-2xl font-bold text-gray-900">考勤管理</h1>
                        <div class="flex items-center space-x-4">
                            <span class="text-gray-600">{{ formatDate(new Date()) }}</span>
                            <button class="p-2 bg-white rounded-full shadow-sm text-gray-600 hover:text-primary refresh-btn" @click="loadAttendanceData">
                                <i class="fa fa-refresh"></i>
                            </button>
                        </div>
                    </div>
                     
                    <!-- 打卡操作 -->
                    <div class="bg-white rounded-lg shadow-sm p-6 mb-6">
                        <h3 class="text-lg font-medium text-gray-900 mb-4">今日打卡</h3>
                        <div class="flex items-center space-x-4">
                            <div class="flex-1">
                                <p class="text-sm text-gray-500 mb-1">当前时间</p>
                                <p class="text-xl font-bold text-gray-900">{{ formatTime(new Date()) }}</p>
                            </div>
                            <div v-if="!isTodayCheckedIn" class="flex-1 text-center">
                                <button class="btn btn-primary w-full py-6" @click="checkIn">
                                    <i class="fa fa-sign-in mr-2"></i>签到打卡
                                </button>
                            </div>
                            <div v-else-if="!isTodayCheckedOut" class="flex-1 text-center">
                                <div class="mb-2">
                                    <p class="text-sm text-gray-500">签到时间</p>
                                    <p class="text-lg font-medium text-gray-900">{{ formatTime(todayCheckInTime) }}</p>
                                </div>
                                <button class="btn btn-secondary w-full py-6" @click="checkOut">
                                    <i class="fa fa-sign-out mr-2"></i>签退打卡
                                </button>
                            </div>
                            <div v-else class="flex-1 text-center">
                                <div class="mb-2">
                                    <p class="text-sm text-gray-500">签到时间</p>
                                    <p class="text-lg font-medium text-gray-900">{{ formatTime(todayCheckInTime) }}</p>
                                </div>
                                <div class="mb-2">
                                    <p class="text-sm text-gray-500">签退时间</p>
                                    <p class="text-lg font-medium text-gray-900">{{ formatTime(todayCheckOutTime) }}</p>
                                </div>
                                <p class="text-success text-sm mt-2">
                                    <i class="fa fa-check-circle mr-1"></i>今日打卡已完成
                                </p>
                            </div>
                        </div>
                    </div>
                     
                    <!-- 考勤统计卡片 -->
                    <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
                        <div class="bg-white rounded-lg shadow-sm p-6 dashboard-card card-hover">
                            <div class="flex items-center justify-between">
                                <div>
                                    <p class="text-gray-500 text-sm">出勤天数</p>
                                    <h3 class="text-2xl font-bold text-gray-900 mt-1">{{ monthlyAttendanceStats.attendanceDays }}</h3>
                                    <p v-if="monthlyAttendanceStats.percentageChange > 0" class="text-success text-xs mt-2">
                                        <i class="fa fa-arrow-up mr-1"></i>
                                        {{ monthlyAttendanceStats.percentageChange }}% 较上月
                                    </p>
                                    <p v-else-if="monthlyAttendanceStats.percentageChange < 0" class="text-danger text-xs mt-2">
                                        <i class="fa fa-arrow-down mr-1"></i>
                                        {{ Math.abs(monthlyAttendanceStats.percentageChange) }}% 较上月
                                    </p>
                                </div>
                                <div class="w-12 h-12 bg-green-100 rounded-full flex items-center justify-center text-green-500">
                                    <i class="fa fa-check-circle text-xl"></i>
                                </div>
                            </div>
                        </div>
                         
                        <div class="bg-white rounded-lg shadow-sm p-6 dashboard-card card-hover" style="animation-delay: 0.1s;">
                            <div class="flex items-center justify-between">
                                <div>
                                    <p class="text-gray-500 text-sm">迟到次数</p>
                                    <h3 class="text-2xl font-bold text-gray-900 mt-1">{{ monthlyAttendanceStats.lateCount }}</h3>
                                    <p v-if="monthlyAttendanceStats.latePercentageChange > 0" class="text-danger text-xs mt-2">
                                        <i class="fa fa-arrow-up mr-1"></i>
                                        {{ monthlyAttendanceStats.latePercentageChange }}% 较上月
                                    </p>
                                    <p v-else-if="monthlyAttendanceStats.latePercentageChange < 0" class="text-success text-xs mt-2">
                                        <i class="fa fa-arrow-down mr-1"></i>
                                        {{ Math.abs(monthlyAttendanceStats.latePercentageChange) }}% 较上月
                                    </p>
                                </div>
                                <div class="w-12 h-12 bg-yellow-100 rounded-full flex items-center justify-center text-yellow-500">
                                    <i class="fa fa-clock-o text-xl"></i>
                                </div>
                            </div>
                        </div>
                         
                        <div class="bg-white rounded-lg shadow-sm p-6 dashboard-card card-hover" style="animation-delay: 0.2s;">
                            <div class="flex items-center justify-between">
                                <div>
                                    <p class="text-gray-500 text-sm">早退次数</p>
                                    <h3 class="text-2xl font-bold text-gray-900 mt-1">{{ monthlyAttendanceStats.earlyLeaveCount }}</h3>
                                    <p v-if="monthlyAttendanceStats.earlyLeavePercentageChange > 0" class="text-danger text-xs mt-2">
                                        <i class="fa fa-arrow-up mr-1"></i>
                                        {{ monthlyAttendanceStats.earlyLeavePercentageChange }}% 较上月
                                    </p>
                                    <p v-else-if="monthlyAttendanceStats.earlyLeavePercentageChange < 0" class="text-success text-xs mt-2">
                                        <i class="fa fa-arrow-down mr-1"></i>
                                        {{ Math.abs(monthlyAttendanceStats.earlyLeavePercentageChange) }}% 较上月
                                    </p>
                                </div>
                                <div class="w-12 h-12 bg-orange-100 rounded-full flex items-center justify-center text-orange-500">
                                    <i class="fa fa-fast-forward text-xl"></i>
                                </div>
                            </div>
                        </div>
                         
                        <div class="bg-white rounded-lg shadow-sm p-6 dashboard-card card-hover" style="animation-delay: 0.3s;">
                            <div class="flex items-center justify-between">
                                <div>
                                    <p class="text-gray-500 text-sm">缺勤天数</p>
                                    <h3 class="text-2xl font-bold text-gray-900 mt-1">{{ monthlyAttendanceStats.absentDays }}</h3>
                                    <p v-if="monthlyAttendanceStats.absentPercentageChange > 0" class="text-danger text-xs mt-2">
                                        <i class="fa fa-arrow-up mr-1"></i>
                                        {{ monthlyAttendanceStats.absentPercentageChange }}% 较上月
                                    </p>
                                    <p v-else-if="monthlyAttendanceStats.absentPercentageChange < 0" class="text-success text-xs mt-2">
                                        <i class="fa fa-arrow-down mr-1"></i>
                                        {{ Math.abs(monthlyAttendanceStats.absentPercentageChange) }}% 较上月
                                    </p>
                                </div>
                                <div class="w-12 h-12 bg-red-100 rounded-full flex items-center justify-center text-red-500">
                                    <i class="fa fa-times-circle text-xl"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                     
                    <!-- 考勤图表 -->
                    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
                        <div class="bg-white rounded-lg shadow-sm p-6">
                            <div class="flex items-center justify-between mb-4">
                                <h3 class="text-lg font-medium text-gray-900">考勤趋势</h3>
                                <div class="relative">
                                    <select v-model="attendanceChartPeriod" class="input-field pr-8 text-sm" @change="updateAttendanceCharts">
                                        <option value="week">本周</option>
                                        <option value="month">本月</option>
                                        <option value="quarter">本季度</option>
                                    </select>
                                </div>
                            </div>
                            <div class="h-64">
                                <canvas ref="attendanceTrendChart"></canvas>
                            </div>
                        </div>
                         
                        <div class="bg-white rounded-lg shadow-sm p-6">
                            <h3 class="text-lg font-medium text-gray-900 mb-4">考勤类型分布</h3>
                            <div class="h-64">
                                <canvas ref="attendanceTypeChart"></canvas>
                            </div>
                        </div>
                    </div>
                     
                    <!-- 日历视图和记录列表 -->
                    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
                        <!-- 日历视图 -->
                        <div class="bg-white rounded-lg shadow-sm p-6">
                            <div class="flex items-center justify-between mb-4">
                                <button @click="previousMonth" class="text-gray-500 hover:text-primary"><i class="fa fa-chevron-left"></i></button>
                                <h3 class="text-lg font-medium text-gray-900">{{ currentMonthDisplay }}</h3>
                                <button @click="nextMonth" class="text-gray-500 hover:text-primary"><i class="fa fa-chevron-right"></i></button>
                            </div>
                            
                            <!-- 日历头部 -->
                            <div class="grid grid-cols-7 mb-2">
                                <div class="text-center text-sm font-medium text-gray-500">日</div>
                                <div class="text-center text-sm font-medium text-gray-500">一</div>
                                <div class="text-center text-sm font-medium text-gray-500">二</div>
                                <div class="text-center text-sm font-medium text-gray-500">三</div>
                                <div class="text-center text-sm font-medium text-gray-500">四</div>
                                <div class="text-center text-sm font-medium text-gray-500">五</div>
                                <div class="text-center text-sm font-medium text-gray-500">六</div>
                            </div>
                            
                            <!-- 日历单元格 -->
                            <div class="grid grid-cols-7 gap-1">
                                <div v-for="n in emptyStartCells" :key="`empty-${n}`" class="h-12 flex items-center justify-center text-gray-300"></div>
                                <div v-for="day in calendarDays" :key="day.day" class="h-12 flex flex-col items-center justify-center rounded-lg border cursor-pointer hover:bg-gray-50 transition-colors" :class="{ 'bg-primary/10 border-primary': day.isToday, 'bg-gray-100': day.isWeekend }">
                                    <span :class="{ 'text-primary font-medium': day.isToday }">
                                        {{ day.day }}
                                    </span>
                                    <span v-if="day.status === 'present'" class="text-xs text-green-500 mt-1">
                                        <i class="fa fa-check-circle"></i>
                                    </span>
                                    <span v-else-if="day.status === 'late'" class="text-xs text-yellow-500 mt-1">
                                        <i class="fa fa-clock-o"></i>
                                    </span>
                                    <span v-else-if="day.status === 'early'" class="text-xs text-orange-500 mt-1">
                                        <i class="fa fa-fast-forward"></i>
                                    </span>
                                    <span v-else-if="day.status === 'absent'" class="text-xs text-red-500 mt-1">
                                        <i class="fa fa-times-circle"></i>
                                    </span>
                                </div>
                            </div>
                        </div>
                         
                        <!-- 考勤记录列表 -->
                        <div class="bg-white rounded-lg shadow-sm p-6 lg:col-span-2">
                            <h3 class="text-lg font-medium text-gray-900 mb-4">考勤记录</h3>
                            <div class="overflow-x-auto">
                                <table class="min-w-full divide-y divide-gray-200">
                                    <thead class="bg-gray-50">
                                        <tr>
                                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">日期</th>
                                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">签到时间</th>
                                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">签退时间</th>
                                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">工作时长</th>
                                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
                                        </tr>
                                    </thead>
                                    <tbody class="bg-white divide-y divide-gray-200">
                                        <tr v-for="record in attendanceRecords.slice(0, 10)" :key="record.id" class="hover:bg-gray-50 transition-colors">
                                            <td class="table-cell">{{ formatDate(record.date) }}</td>
                                            <td class="table-cell">{{ record.check_in_time ? formatTime(record.check_in_time) : '-' }}</td>
                                            <td class="table-cell">{{ record.check_out_time ? formatTime(record.check_out_time) : '-' }}</td>
                                            <td class="table-cell">{{ record.work_duration || '-' }}</td>
                                            <td class="table-cell">
                                                <span v-if="record.status === 'present'" class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
                                                    <i class="fa fa-check-circle mr-1"></i>出勤
                                                </span>
                                                <span v-else-if="record.status === 'late'" class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800">
                                                    <i class="fa fa-clock-o mr-1"></i>迟到
                                                </span>
                                                <span v-else-if="record.status === 'early'" class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-orange-100 text-orange-800">
                                                    <i class="fa fa-fast-forward mr-1"></i>早退
                                                </span>
                                                <span v-else-if="record.status === 'absent'" class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800">
                                                    <i class="fa fa-times-circle mr-1"></i>缺勤
                                                </span>
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                            <div class="mt-4 text-center text-sm text-gray-500" v-if="attendanceRecords.length === 0">
                                <i class="fa fa-calendar-o text-4xl mb-2"></i>
                                <p>暂无考勤记录</p>
                            </div>
                        </div>
                    </div>
                </div>
            </main>
        </div>
        
        <!-- 添加用户模态框 -->
        <div v-if="showAddUser" class="fixed inset-0 z-50 flex items-center justify-center">
            <div class="absolute inset-0 bg-gray-600 bg-opacity-50 transition-opacity"></div>
            <div class="bg-white rounded-lg shadow-xl max-w-md w-full mx-4 relative z-10">
                <div class="p-6">
                    <div class="flex items-center justify-between mb-4">
                        <h3 class="text-lg font-medium text-gray-900">添加用户</h3>
                        <button class="text-gray-400 hover:text-gray-500" @click="showAddUser = false">
                            <i class="fa fa-times"></i>
                        </button>
                    </div>
                    
                    <form @submit.prevent="addUser" class="space-y-4">
                        <div>
                            <label for="full_name" class="block text-sm font-medium text-gray-700 mb-1">姓名</label>
                            <input type="text" id="full_name" v-model="newUser.full_name" class="input-field" placeholder="请输入姓名">
                        </div>
                        
                        <div>
                            <label for="email" class="block text-sm font-medium text-gray-700 mb-1">邮箱</label>
                            <input type="email" id="email" v-model="newUser.email" class="input-field" placeholder="请输入邮箱">
                        </div>
                        
                        <div>
                            <label for="department_id" class="block text-sm font-medium text-gray-700 mb-1">部门</label>
                            <select id="department_id" v-model="newUser.department_id" class="input-field">
                                <option value="">请选择部门</option>
                                <option v-for="department in departments" :key="department.id" :value="department.id">
                                    {{ department.name }}
                                </option>
                            </select>
                        </div>
                        
                        <div>
                            <label for="position" class="block text-sm font-medium text-gray-700 mb-1">职位</label>
                            <input type="text" id="position" v-model="newUser.position" class="input-field" placeholder="请输入职位">
                        </div>
                        
                        <div class="flex justify-end space-x-3 pt-4 border-t">
                            <button type="button" class="btn btn-secondary" @click="showAddUser = false">取消</button>
                            <button type="submit" class="btn btn-primary">添加</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
        
        <!-- 添加部门模态框 -->
        <div v-if="showAddDepartment" class="fixed inset-0 z-50 flex items-center justify-center">
            <div class="absolute inset-0 bg-gray-600 bg-opacity-50 transition-opacity"></div>
            <div class="bg-white rounded-lg shadow-xl max-w-md w-full mx-4 relative z-10">
                <div class="p-6">
                    <div class="flex items-center justify-between mb-4">
                        <h3 class="text-lg font-medium text-gray-900">添加部门</h3>
                        <button class="text-gray-400 hover:text-gray-500" @click="showAddDepartment = false">
                            <i class="fa fa-times"></i>
                        </button>
                    </div>
                    
                    <form @submit.prevent="addDepartment" class="space-y-4">
                        <div>
                            <label for="dept_name" class="block text-sm font-medium text-gray-700 mb-1">部门名称</label>
                            <input type="text" id="dept_name" v-model="newDepartment.name" class="input-field" placeholder="请输入部门名称">
                        </div>
                        
                        <div>
                            <label for="description" class="block text-sm font-medium text-gray-700 mb-1">描述</label>
                            <textarea id="description" v-model="newDepartment.description" class="input-field" rows="3" placeholder="请输入部门描述"></textarea>
                        </div>
                        
                        <div>
                            <label for="manager_id" class="block text-sm font-medium text-gray-700 mb-1">负责人</label>
                            <select id="manager_id" v-model="newDepartment.manager_id" class="input-field">
                                <option value="">请选择负责人</option>
                                <option v-for="user in users" :key="user.id" :value="user.id">
                                    {{ user.full_name }}
                                </option>
                            </select>
                        </div>
                        
                        <div class="flex justify-end space-x-3 pt-4 border-t">
                            <button type="button" class="btn btn-secondary" @click="showAddDepartment = false">取消</button>
                            <button type="submit" class="btn btn-primary">添加</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
        
        <!-- 添加项目模态框 -->
        <div v-if="showAddProject" class="fixed inset-0 z-50 flex items-center justify-center">
            <div class="absolute inset-0 bg-gray-600 bg-opacity-50 transition-opacity"></div>
            <div class="bg-white rounded-lg shadow-xl max-w-lg w-full mx-4 relative z-10">
                <div class="p-6">
                    <div class="flex items-center justify-between mb-4">
                        <h3 class="text-lg font-medium text-gray-900">添加项目</h3>
                        <button class="text-gray-400 hover:text-gray-500" @click="showAddProject = false">
                            <i class="fa fa-times"></i>
                        </button>
                    </div>
                    
                    <form @submit.prevent="addProject" class="space-y-4">
                        <div>
                            <label for="project_name" class="block text-sm font-medium text-gray-700 mb-1">项目名称</label>
                            <input type="text" id="project_name" v-model="newProject.name" class="input-field" placeholder="请输入项目名称">
                        </div>
                        
                        <div>
                            <label for="project_description" class="block text-sm font-medium text-gray-700 mb-1">项目描述</label>
                            <textarea id="project_description" v-model="newProject.description" class="input-field" rows="3" placeholder="请输入项目描述"></textarea>
                        </div>
                        
                        <div>
                            <label for="manager_name" class="block text-sm font-medium text-gray-700 mb-1">负责人姓名</label>
                            <input type="text" id="manager_name" v-model="newProject.manager_name" class="input-field" placeholder="请输入负责人姓名">
                        </div>
                        
                        <div>
                            <label for="project_department_id" class="block text-sm font-medium text-gray-700 mb-1">所属部门</label>
                            <select id="project_department_id" v-model="newProject.department_id" class="input-field">
                                <option value="">请选择部门</option>
                                <option v-for="department in departments" :key="department.id" :value="department.id">
                                    {{ department.name }}
                                </option>
                            </select>
                        </div>
                        
                        <div>
                            <label for="budget" class="block text-sm font-medium text-gray-700 mb-1">预算</label>
                            <input type="number" id="budget" v-model.number="newProject.budget" class="input-field" placeholder="请输入预算金额">
                        </div>
                        
                        <div>
                            <label for="progress" class="block text-sm font-medium text-gray-700 mb-1">初始进度</label>
                            <input type="number" id="progress" v-model.number="newProject.progress" class="input-field" placeholder="请输入初始进度" min="0" max="100">
                        </div>
                        
                        <div>
                            <label for="status" class="block text-sm font-medium text-gray-700 mb-1">项目状态</label>
                            <select id="status" v-model="newProject.status" class="input-field">
                                <option value="planning">规划中</option>
                                <option value="in_progress">进行中</option>
                                <option value="completed">已完成</option>
                            </select>
                        </div>
                        
                        <div class="flex justify-end space-x-3 pt-4 border-t">
                            <button type="button" class="btn btn-secondary" @click="showAddProject = false">取消</button>
                            <button type="submit" class="btn btn-primary">添加</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
        
        <!-- 编辑用户模态框 -->
        <div v-if="showEditUserModal" class="fixed inset-0 z-50 flex items-center justify-center">
            <div class="absolute inset-0 bg-gray-600 bg-opacity-50 transition-opacity"></div>
            <div class="bg-white rounded-lg shadow-xl max-w-lg w-full mx-4 relative z-10">
                <div class="p-6">
                    <div class="flex items-center justify-between mb-4">
                        <h3 class="text-lg font-medium text-gray-900">编辑用户</h3>
                        <button class="text-gray-400 hover:text-gray-500" @click="showEditUserModal = false">
                            <i class="fa fa-times"></i>
                        </button>
                    </div>
                    
                    <form @submit.prevent="saveEditUser" class="space-y-4">
                        <div>
                            <label for="edit-username" class="block text-sm font-medium text-gray-700 mb-1">用户名</label>
                            <input type="text" id="edit-username" v-model="editUserForm.username" class="input-field" placeholder="请输入用户名">
                        </div>
                        
                        <div>
                            <label for="edit-fullname" class="block text-sm font-medium text-gray-700 mb-1">姓名</label>
                            <input type="text" id="edit-fullname" v-model="editUserForm.full_name" class="input-field" placeholder="请输入姓名">
                        </div>
                        
                        <div>
                            <label for="edit-email" class="block text-sm font-medium text-gray-700 mb-1">邮箱</label>
                            <input type="email" id="edit-email" v-model="editUserForm.email" class="input-field" placeholder="请输入邮箱">
                        </div>
                        
                        <div>
                            <label for="edit-department" class="block text-sm font-medium text-gray-700 mb-1">所属部门</label>
                            <select id="edit-department" v-model="editUserForm.department_id" class="input-field">
                                <option value="">请选择部门</option>
                                <option v-for="department in departments" :key="department.id" :value="department.id">
                                    {{ department.name }}
                                </option>
                            </select>
                        </div>
                        
                        <div>
                            <label class="flex items-center">
                                <input type="checkbox" v-model="editUserForm.is_active" class="form-checkbox text-primary rounded">
                                <span class="ml-2 text-gray-700">激活状态</span>
                            </label>
                        </div>
                        
                        <div v-if="currentUser?.is_superuser">
                            <label class="flex items-center">
                                <input type="checkbox" v-model="editUserForm.is_admin" class="form-checkbox text-primary rounded">
                                <span class="ml-2 text-gray-700">管理员权限</span>
                            </label>
                        </div>
                        
                        <div class="flex justify-end space-x-3 pt-4 border-t">
                            <button type="button" class="btn btn-secondary" @click="showEditUserModal = false">取消</button>
                            <button type="submit" class="btn btn-primary">保存</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
        
        <!-- 编辑部门模态框 -->
        <div v-if="showEditDepartmentModal" class="fixed inset-0 z-50 flex items-center justify-center">
            <div class="absolute inset-0 bg-gray-600 bg-opacity-50 transition-opacity"></div>
            <div class="bg-white rounded-lg shadow-xl max-w-lg w-full mx-4 relative z-10">
                <div class="p-6">
                    <div class="flex items-center justify-between mb-4">
                        <h3 class="text-lg font-medium text-gray-900">编辑部门</h3>
                        <button class="text-gray-400 hover:text-gray-500" @click="showEditDepartmentModal = false">
                            <i class="fa fa-times"></i>
                        </button>
                    </div>
                    
                    <form @submit.prevent="saveEditDepartment" class="space-y-4">
                        <div>
                            <label for="edit-dept-name" class="block text-sm font-medium text-gray-700 mb-1">部门名称</label>
                            <input type="text" id="edit-dept-name" v-model="editDepartmentForm.name" class="input-field" placeholder="请输入部门名称">
                        </div>
                        
                        <div>
                            <label for="edit-dept-description" class="block text-sm font-medium text-gray-700 mb-1">描述</label>
                            <textarea id="edit-dept-description" v-model="editDepartmentForm.description" class="input-field" rows="3" placeholder="请输入部门描述"></textarea>
                        </div>
                        
                        <div class="flex justify-end space-x-3 pt-4 border-t">
                            <button type="button" class="btn btn-secondary" @click="showEditDepartmentModal = false">取消</button>
                            <button type="submit" class="btn btn-primary">保存</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
        
        <!-- 编辑项目模态框 -->
        <div v-if="showEditProjectModal" class="fixed inset-0 z-50 flex items-center justify-center">
            <div class="absolute inset-0 bg-gray-600 bg-opacity-50 transition-opacity"></div>
            <div class="bg-white rounded-lg shadow-xl max-w-lg w-full mx-4 relative z-10">
                <div class="p-6">
                    <div class="flex items-center justify-between mb-4">
                        <h3 class="text-lg font-medium text-gray-900">编辑项目</h3>
                        <button class="text-gray-400 hover:text-gray-500" @click="showEditProjectModal = false">
                            <i class="fa fa-times"></i>
                        </button>
                    </div>
                    
                    <form @submit.prevent="saveEditProject" class="space-y-4">
                        <div>
                            <label for="edit-project-name" class="block text-sm font-medium text-gray-700 mb-1">项目名称</label>
                            <input type="text" id="edit-project-name" v-model="editProjectForm.name" class="input-field" placeholder="请输入项目名称">
                        </div>
                        
                        <div>
                            <label for="edit-project-description" class="block text-sm font-medium text-gray-700 mb-1">项目描述</label>
                            <textarea id="edit-project-description" v-model="editProjectForm.description" class="input-field" rows="3" placeholder="请输入项目描述"></textarea>
                        </div>
                        
                        <div>
                            <label for="edit-project-start-date" class="block text-sm font-medium text-gray-700 mb-1">开始日期</label>
                            <input type="date" id="edit-project-start-date" v-model="editProjectForm.start_date" class="input-field">
                        </div>
                        
                        <div>
                            <label for="edit-project-end-date" class="block text-sm font-medium text-gray-700 mb-1">结束日期</label>
                            <input type="date" id="edit-project-end-date" v-model="editProjectForm.end_date" class="input-field">
                        </div>
                        
                        <div>
                            <label for="edit-project-status" class="block text-sm font-medium text-gray-700 mb-1">项目状态</label>
                            <select id="edit-project-status" v-model="editProjectForm.status" class="input-field">
                                <option value="PLANNING">规划中</option>
                                <option value="IN_PROGRESS">进行中</option>
                                <option value="COMPLETED">已完成</option>
                                <option value="ON_HOLD">暂停中</option>
                                <option value="CANCELLED">已取消</option>
                            </select>
                        </div>
                        
                        <div>
                            <label for="edit-project-manager" class="block text-sm font-medium text-gray-700 mb-1">项目经理</label>
                            <select id="edit-project-manager" v-model="editProjectForm.manager_id" class="input-field">
                                <option value="">请选择项目经理</option>
                                <option v-for="user in users" :key="user.id" :value="user.id">
                                    {{ user.full_name }}
                                </option>
                            </select>
                        </div>
                        
                        <div class="flex justify-end space-x-3 pt-4 border-t">
                            <button type="button" class="btn btn-secondary" @click="showEditProjectModal = false">取消</button>
                            <button type="submit" class="btn btn-primary">保存</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
    
    <script>
        // 配置axios基础URL
        axios.defaults.baseURL = 'http://localhost:8000';
        axios.defaults.withCredentials = true;
        
        const app = Vue.createApp({
            data() {
                return {
                    isLoggedIn: false,
                    username: '',
                    password: '',
                    loginError: '',
                    authView: 'login', // login, register, forgot
                    
                    // 注册相关
                    registerForm: {
                        username: '',
                        email: '',
                        full_name: '',
                        password: '',
                        confirmPassword: ''
                    },
                    registerError: '',
                    registerSuccess: '',
                    isRegistering: false,
                    
                    // 忘记密码相关
                    forgotForm: {
                        email: ''
                    },
                    resetForm: {
                        reset_token: '',
                        new_password: '',
                        confirm_password: ''
                    },
                    forgotError: '',
                    forgotSuccess: '',
                    resetToken: '',
                    isSendingReset: false,
                    isResetting: false,
                    
                    currentView: 'dashboard',
                    users: [],
                    departments: [],
                    projects: [],
                    activeProjects: 0,
                    projectChartInstance: null,
                    departmentChartInstance: null,
                    // 添加功能相关状态
                    showAddUser: false,
                    showAddDepartment: false,
                    showAddProject: false,
                    
                    // 编辑功能相关状态
                    showEditUserModal: false,
                    editUserId: null,
                    editUserForm: {},
                    showEditDepartmentModal: false,
                    editDepartmentId: null,
                    editDepartmentForm: {},
                    showEditProjectModal: false,
                    editProjectId: null,
                    editProjectForm: {},
                    // 表单数据
                    newUser: { full_name: '', email: '', department_id: '', position: '' },
                    newDepartment: { name: '', description: '', manager_id: '' },
                    newProject: { name: '', description: '', manager_name: '', department_id: '', budget: 0, progress: 0, status: 'planning' },
                    // 考勤相关数据
                    attendanceRecords: [],
                    attendanceChartPeriod: 'month',
                    attendanceTrendChartInstance: null,
                    attendanceTypeChartInstance: null,
                    currentMonth: new Date().getMonth(),
                    currentYear: new Date().getFullYear(),
                    calendarDays: [],
                    emptyStartCells: [],
                    currentMonthDisplay: '',
                    monthlyAttendanceStats: {
                        attendanceDays: 0,
                        lateCount: 0,
                        earlyLeaveCount: 0,
                        absentDays: 0,
                        percentageChange: 0,
                        latePercentageChange: 0,
                        earlyLeavePercentageChange: 0,
                        absentPercentageChange: 0
                    },
                    recentAttendanceRecords: [],
                    isTodayCheckedIn: false,
                    isTodayCheckedOut: false,
                    todayCheckInTime: null,
                    todayCheckOutTime: null
                };
            },
            methods: {
                // 初始化应用时检查localStorage中的token
                async initApp() {
                    try {
                        const token = localStorage.getItem('token');
                        const savedUser = localStorage.getItem('currentUser');
                        
                        if (token) {
                            // 设置axios默认的Authorization头
                            axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
                            
                            // 尝试验证token是否有效
                            try {
                                if (savedUser) {
                                    this.currentUser = JSON.parse(savedUser);
                                } else {
                                    const userResponse = await axios.get('/auth/me');
                                    this.currentUser = userResponse.data;
                                    localStorage.setItem('currentUser', JSON.stringify(userResponse.data));
                                }
                                
                                this.isLoggedIn = true;
                                
                                // 普通用户登录后默认跳转到考勤管理
                                if (!this.currentUser?.is_superuser) {
                                    this.currentView = 'attendance';
                                }
                                
                                await this.loadAllData();
                            } catch (error) {
                                console.error('自动登录失败，需要重新登录:', error);
                                localStorage.removeItem('token');
                                localStorage.removeItem('currentUser');
                                this.isLoggedIn = false;
                                this.authView = 'login'; // 确保显示登录页面
                            }
                        } else {
                            // 如果没有token，显示登录页面并生成模拟数据供预览
                            this.authView = 'login';
                            await this.generateMockDataForPreview();
                        }
                    } catch (error) {
                        console.error('初始化应用失败:', error);
                    }
                },
                
                async login() {
                    try {
                        // 使用完整URL或设置axios默认基础URL
                        const baseUrl = window.location.protocol + '//' + window.location.hostname + ':8000';
                        
                        // 方法1: 使用URLSearchParams
                        const formData = new URLSearchParams();
                        formData.append('username', this.username);
                        formData.append('password', this.password);
                        
                        console.log('登录请求URL:', baseUrl + '/auth/login');
                        console.log('登录请求数据:', formData.toString());
                        
                        const response = await axios.post(baseUrl + '/auth/login', formData, {
                            headers: {
                                'Content-Type': 'application/x-www-form-urlencoded'
                            },
                            withCredentials: true, // 允许携带Cookie
                            timeout: 5000 // 设置超时时间
                        });
                        
                        const token = response.data.access_token;
                        localStorage.setItem('token', token);
                        localStorage.setItem('username', this.username);
                        
                        // 获取当前用户信息
                        try {
                            console.log('获取用户信息URL:', baseUrl + '/auth/me');
                            const userResponse = await axios.get(baseUrl + '/auth/me', {
                                headers: {
                                    'Authorization': `Bearer ${token}`
                                },
                                withCredentials: true,
                                timeout: 5000
                            });
                            this.currentUser = userResponse.data;
                            localStorage.setItem('currentUser', JSON.stringify(userResponse.data));
                        } catch (userError) {
                            console.error('获取用户信息失败:', userError);
                        }
                        
                        this.isLoggedIn = true;
                        this.loginError = '';
                        
                        // 普通用户登录后默认跳转到考勤管理
                        if (!this.currentUser?.is_superuser) {
                            this.currentView = 'attendance';
                        }
                        
                        await this.loadAllData();
                    } catch (error) {
                        this.loginError = error.response?.data?.detail || '登录失败，请重试';
                        console.error('Login error:', error);
                    }
                },
                
                async register() {
                    if (this.registerForm.password !== this.registerForm.confirmPassword) {
                        this.registerError = '两次输入的密码不一致';
                        return;
                    }
                    
                    if (this.registerForm.password.length < 6) {
                        this.registerError = '密码长度至少为6位';
                        return;
                    }
                    
                    this.isRegistering = true;
                    this.registerError = '';
                    this.registerSuccess = '';
                    
                    try {
                        const response = await axios.post('/auth/register', this.registerForm);
                        this.registerSuccess = '注册成功！正在跳转到登录页面...';
                        
                        // 清空表单
                        this.registerForm = {
                            username: '',
                            email: '',
                            full_name: '',
                            password: '',
                            confirmPassword: ''
                        };
                        
                        // 2秒后跳转到登录页面
                        setTimeout(() => {
                            this.authView = 'login';
                            this.registerSuccess = '';
                        }, 2000);
                        
                    } catch (error) {
                        this.registerError = error.response?.data?.detail || '注册失败，请重试';
                        console.error('Register error:', error);
                    } finally {
                        this.isRegistering = false;
                    }
                },
                
                async forgotPassword() {
                    this.isSendingReset = true;
                    this.forgotError = '';
                    this.forgotSuccess = '';
                    this.resetToken = '';
                    
                    try {
                        const response = await axios.post('/auth/forgot-password', this.forgotForm);
                        this.resetToken = response.data.reset_token;
                        this.forgotSuccess = '重置链接已生成！请查看您的邮箱';
                        
                        // 预填充重置令牌
                        this.resetForm.reset_token = this.resetToken;
                        
                    } catch (error) {
                        this.forgotError = error.response?.data?.detail || '发送失败，请重试';
                        console.error('Forgot password error:', error);
                    } finally {
                        this.isSendingReset = false;
                    }
                },
                
                async resetPassword() {
                    if (this.resetForm.new_password !== this.resetForm.confirm_password) {
                        this.forgotError = '两次输入的密码不一致';
                        return;
                    }
                    
                    if (this.resetForm.new_password.length < 6) {
                        this.forgotError = '密码长度至少为6位';
                        return;
                    }
                    
                    this.isResetting = true;
                    this.forgotError = '';
                    
                    try {
                        await axios.post('/auth/reset-password', {
                            reset_token: this.resetForm.reset_token,
                            new_password: this.resetForm.new_password
                        });
                        
                        this.forgotSuccess = '密码重置成功！正在跳转到登录页面...';
                        
                        // 清空表单
                        this.forgotForm = { email: '' };
                        this.resetForm = {
                            reset_token: '',
                            new_password: '',
                            confirm_password: ''
                        };
                        this.resetToken = '';
                        
                        // 2秒后跳转到登录页面
                        setTimeout(() => {
                            this.authView = 'login';
                            this.forgotSuccess = '';
                        }, 2000);
                        
                    } catch (error) {
                        this.forgotError = error.response?.data?.detail || '重置失败，请重试';
                        console.error('Reset password error:', error);
                    } finally {
                        this.isResetting = false;
                    }
                },
                
                async changePassword() {
                    // 修改密码功能可以添加到用户设置页面
                    const newPassword = prompt('请输入新密码：');
                    if (!newPassword || newPassword.length < 6) {
                        alert('密码长度至少为6位');
                        return;
                    }
                    
                    const currentPassword = prompt('请输入当前密码：');
                    if (!currentPassword) {
                        return;
                    }
                    
                    try {
                        await axios.post('/auth/change-password', {
                            current_password: currentPassword,
                            new_password: newPassword
                        }, {
                            headers: {
                                'Authorization': `Bearer ${localStorage.getItem('token')}`
                            }
                        });
                        
                        alert('密码修改成功！');
                    } catch (error) {
                        alert(error.response?.data?.detail || '密码修改失败，请重试');
                        console.error('Change password error:', error);
                    }
                },
                
                logout() {
                    this.isLoggedIn = false;
                    this.username = '';
                    this.password = '';
                    this.currentView = 'dashboard';
                    this.authView = 'login';
                    this.users = [];
                    this.departments = [];
                    this.projects = [];
                    this.activeProjects = 0;
                    localStorage.removeItem('token');
                    localStorage.removeItem('username');
                    this.destroyCharts();
                },
                 
                async loadAllData() {
                    try {
                        // 设置axios默认配置
                        axios.defaults.headers.common['Authorization'] = `Bearer ${localStorage.getItem('token')}`;
                        
                        await this.loadUsers();
                        await this.loadDepartments();
                        await this.loadProjects();
                        
                        if (this.users.length === 0 || this.departments.length === 0 || this.projects.length === 0) {
                            this.generateMockData();
                        }
                        
                        await this.initializeCharts();
                    } catch (error) {
                        console.error('Error loading data:', error);
                        this.generateMockData();
                        await this.initializeCharts();
                    }
                },
                
                // 为预览目的生成模拟数据，不需要登录
                generateMockDataForPreview() {
                    try {
                        this.generateMockData();
                        this.initializeCharts();
                    } catch (error) {
                        console.error('生成预览数据失败:', error);
                    }
                },
                 
                async loadUsers() {
                    try {
                        const response = await axios.get('/employees');
                        this.users = response.data;
                    } catch (error) {
                        console.error('Error loading users:', error);
                    }
                },
                
                async loadDepartments() {
                    try {
                        const response = await axios.get('/departments');
                        this.departments = response.data;
                    } catch (error) {
                        console.error('Error loading departments:', error);
                    }
                },
                
                async loadProjects() {
                    try {
                        const response = await axios.get('/projects');
                        this.projects = response.data;
                        this.activeProjects = this.projects.filter(p => p.status === 'in_progress').length;
                    } catch (error) {
                        console.error('Error loading projects:', error);
                    }
                },
                 
                generateMockData() {
                    // 生成模拟用户数据
                    this.users = [
                        { id: 1, full_name: '张三', email: 'zhangsan@example.com', department_id: 1, position: '技术总监', created_at: '2023-01-15' },
                        { id: 2, full_name: '李四', email: 'lisi@example.com', department_id: 1, position: '高级开发工程师', created_at: '2023-02-10' },
                        { id: 3, full_name: '王五', email: 'wangwu@example.com', department_id: 1, position: 'UI设计师', created_at: '2023-03-05' },
                        { id: 4, full_name: '赵六', email: 'zhaoliu@example.com', department_id: 2, position: '市场经理', created_at: '2023-01-20' },
                        { id: 5, full_name: '钱七', email: 'qianqi@example.com', department_id: 2, position: '市场专员', created_at: '2023-03-15' },
                        { id: 6, full_name: '孙八', email: 'sunba@example.com', department_id: 3, position: '运维总监', created_at: '2023-02-01' },
                        { id: 7, full_name: '周九', email: 'zhoujiu@example.com', department_id: 3, position: '运维工程师', created_at: '2023-04-10' },
                        { id: 8, full_name: '吴十', email: 'wushi@example.com', department_id: 4, position: '人事经理', created_at: '2023-01-05' },
                        { id: 9, full_name: '郑十一', email: 'zhengshiyi@example.com', department_id: 5, position: '财务总监', created_at: '2023-01-25' },
                        { id: 10, full_name: '王十二', email: 'wangshier@example.com', department_id: 1, position: '前端开发工程师', created_at: '2023-04-20' },
                        { id: 11, full_name: '李十三', email: 'lishisan@example.com', department_id: 1, position: '后端开发工程师', created_at: '2023-05-05' },
                        { id: 12, full_name: '张十四', email: 'zhangshisi@example.com', department_id: 5, position: '财务专员', created_at: '2023-05-15' },
                        { id: 13, full_name: '刘十五', email: 'liushiwu@example.com', department_id: 4, position: '招聘专员', created_at: '2023-06-01' },
                        { id: 14, full_name: '陈十六', email: 'chenshiliu@example.com', department_id: 2, position: '内容策划', created_at: '2023-06-10' },
                        { id: 15, full_name: '杨十七', email: 'yangshiqi@example.com', department_id: 1, position: '产品经理', created_at: '2023-06-20' }
                    ];
                     
                    // 生成模拟部门数据
                    this.departments = [
                        { id: 1, name: '研发部', manager_id: 1, description: '负责产品研发与创新', employee_count: 6, created_at: '2023-01-01' },
                        { id: 2, name: '市场部', manager_id: 4, description: '负责市场推广与用户增长', employee_count: 3, created_at: '2023-01-01' },
                        { id: 3, name: '运维部', manager_id: 6, description: '负责系统运维与安全保障', employee_count: 2, created_at: '2023-01-01' },
                        { id: 4, name: '人力资源部', manager_id: 8, description: '负责人力资源管理与人才招聘', employee_count: 2, created_at: '2023-01-01' },
                        { id: 5, name: '财务部', manager_id: 9, description: '负责财务管理与资金运作', employee_count: 2, created_at: '2023-01-01' }
                    ];
                     
                    // 生成模拟项目数据
                    this.projects = [
                        { id: 1, name: '企业管理系统开发', manager_name: '张三', progress: 75, status: 'in_progress', department_id: 1, budget: 500000, start_date: '2023-03-01', end_date: '2023-10-31' },
                        { id: 2, name: '市场推广活动', manager_name: '赵六', progress: 45, status: 'in_progress', department_id: 2, budget: 150000, start_date: '2023-05-01', end_date: '2023-07-31' },
                        { id: 3, name: '服务器升级项目', manager_name: '孙八', progress: 90, status: 'in_progress', department_id: 3, budget: 100000, start_date: '2023-06-15', end_date: '2023-07-15' },
                        { id: 4, name: '产品设计改版', manager_name: '王五', progress: 100, status: 'completed', department_id: 1, budget: 80000, start_date: '2023-02-01', end_date: '2023-03-15' },
                        { id: 5, name: '新功能规划', manager_name: '杨十七', progress: 10, status: 'planning', department_id: 1, budget: 120000, start_date: '2023-08-01', end_date: '2023-12-31' },
                        { id: 6, name: '年度招聘计划', manager_name: '吴十', progress: 60, status: 'in_progress', department_id: 4, budget: 50000, start_date: '2023-01-01', end_date: '2023-12-31' },
                        { id: 7, name: '财务系统升级', manager_name: '郑十一', progress: 80, status: 'in_progress', department_id: 5, budget: 75000, start_date: '2023-04-01', end_date: '2023-06-30' },
                        { id: 8, name: '品牌重塑项目', manager_name: '钱七', progress: 25, status: 'in_progress', department_id: 2, budget: 200000, start_date: '2023-06-01', end_date: '2023-09-30' },
                        { id: 9, name: '员工培训体系', manager_name: '吴十', progress: 100, status: 'completed', department_id: 4, budget: 30000, start_date: '2023-01-15', end_date: '2023-02-15' },
                        { id: 10, name: '数据中心迁移', manager_name: '孙八', progress: 0, status: 'planning', department_id: 3, budget: 300000, start_date: '2023-09-01', end_date: '2023-11-30' }
                    ];
                     
                    this.activeProjects = this.projects.filter(p => p.status === 'in_progress').length;
                },
                 
                async initializeCharts() {
                    // 确保图表实例被销毁
                    this.destroyCharts();
                     
                    // 等待DOM更新
                    await this.$nextTick();
                     
                    // 检查DOM元素是否存在
                    const projectChartCtx = this.$refs.projectChart;
                    const departmentChartCtx = this.$refs.departmentChart;
                     
                    if (projectChartCtx && departmentChartCtx) {
                        // 项目进度柱状图
                        this.projectChartInstance = new Chart(projectChartCtx, {
                            type: 'bar',
                            data: {
                                labels: this.projects.slice(0, 3).map(p => p.name),
                                datasets: [{
                                    label: '完成进度',
                                    data: this.projects.slice(0, 3).map(p => p.progress),
                                    backgroundColor: [
                                        'rgba(255, 99, 132, 0.7)',
                                        'rgba(54, 162, 235, 0.7)',
                                        'rgba(255, 206, 86, 0.7)'
                                    ],
                                    borderColor: [
                                        'rgba(255, 99, 132, 1)',
                                        'rgba(54, 162, 235, 1)',
                                        'rgba(255, 206, 86, 1)'
                                    ],
                                    borderWidth: 1
                                }]
                            },
                            options: {
                                responsive: true,
                                maintainAspectRatio: false,
                                scales: {
                                    y: {
                                        beginAtZero: true,
                                        max: 100,
                                        ticks: {
                                            callback: function(value) {
                                                return value + '%';
                                            }
                                        }
                                    }
                                },
                                plugins: {
                                    tooltip: {
                                        callbacks: {
                                            label: function(context) {
                                                return context.raw + '%';
                                            }
                                        }
                                    }
                                }
                            }
                        });
                         
                        // 部门人员分布环形图
                        const departmentUserCounts = this.departments.map(dept => {
                            return this.users.filter(user => user.department_id === dept.id).length;
                        });
                         
                        this.departmentChartInstance = new Chart(departmentChartCtx, {
                            type: 'doughnut',
                            data: {
                                labels: this.departments.map(d => d.name),
                                datasets: [{
                                    data: departmentUserCounts,
                                    backgroundColor: [
                                        'rgba(255, 99, 132, 0.7)',
                                        'rgba(54, 162, 235, 0.7)',
                                        'rgba(255, 206, 86, 0.7)',
                                        'rgba(75, 192, 192, 0.7)',
                                        'rgba(153, 102, 255, 0.7)'
                                    ],
                                    borderColor: [
                                        'rgba(255, 99, 132, 1)',
                                        'rgba(54, 162, 235, 1)',
                                        'rgba(255, 206, 86, 1)',
                                        'rgba(75, 192, 192, 1)',
                                        'rgba(153, 102, 255, 1)'
                                    ],
                                    borderWidth: 1
                                }]
                            },
                            options: {
                                responsive: true,
                                maintainAspectRatio: false,
                                plugins: {
                                    legend: {
                                        position: 'right'
                                    }
                                }
                            }
                        });
                    }
                },
                 
                destroyCharts() {
                    if (this.projectChartInstance) {
                        this.projectChartInstance.destroy();
                        this.projectChartInstance = null;
                    }
                    if (this.departmentChartInstance) {
                        this.departmentChartInstance.destroy();
                        this.departmentChartInstance = null;
                    }
                },
                 
                refreshData() {
                    this.loadAllData();
                },
                 
                getPercentageChange(oldValue, newValue) {
                    if (oldValue === 0) return 0;
                    return Math.round(((newValue - oldValue) / oldValue) * 100);
                },
                 
                getRecentProjects() {
                    return this.projects.slice(0, 3);
                },
                 
                getRecentActivities() {
                    const now = new Date();
                    const hourAgo = new Date(now.getTime() - 3600000);
                    const twoHoursAgo = new Date(now.getTime() - 7200000);
                    const threeHoursAgo = new Date(now.getTime() - 10800000);
                    const fourHoursAgo = new Date(now.getTime() - 14400000);
                    const sixHoursAgo = new Date(now.getTime() - 21600000);
                    const twelveHoursAgo = new Date(now.getTime() - 43200000);
                    const oneDayAgo = new Date(now.getTime() - 86400000);
                    const twoDaysAgo = new Date(now.getTime() - 172800000);
                    const threeDaysAgo = new Date(now.getTime() - 259200000);
                     
                    return [
                        { id: 1, user: '张三', action: '创建了新项目：企业管理系统开发', time: now },
                        { id: 2, user: '李四', action: '更新了项目进度：市场推广活动 (45%)', time: hourAgo },
                        { id: 3, user: '王五', action: '添加了新用户：杨十七', time: twoHoursAgo },
                        { id: 4, user: '赵六', action: '修改了部门信息：市场部', time: threeHoursAgo },
                        { id: 5, user: '钱七', action: '上传了项目文档：品牌重塑方案', time: fourHoursAgo },
                        { id: 6, user: '孙八', action: '完成了项目：服务器升级项目 (90%)', time: sixHoursAgo },
                        { id: 7, user: '周九', action: '添加了系统维护日志', time: twelveHoursAgo },
                        { id: 8, user: '吴十', action: '处理了5个员工入职手续', time: oneDayAgo },
                        { id: 9, user: '郑十一', action: '完成了财务报表：5月份', time: twoDaysAgo },
                        { id: 10, user: '王十二', action: '修复了系统Bug：前端页面响应慢', time: threeDaysAgo }
                    ];
                },
                 
                formatDate(date) {
                    if (!(date instanceof Date)) {
                        date = new Date(date);
                    }
                    return date.toLocaleString('zh-CN');
                },
                 
                async editUser(id) {
                    try {
                        // 获取用户详情
                        const response = await axios.get(`/users/${id}`);
                        const user = response.data;
                        
                        // 填充编辑表单
                        this.editUserId = user.id;
                        this.editUserForm = {
                            username: user.username,
                            full_name: user.full_name,
                            email: user.email,
                            department_id: user.department_id,
                            is_active: user.is_active,
                            is_admin: user.is_admin
                        };
                        
                        // 显示编辑模态框
                        this.showEditUserModal = true;
                    } catch (error) {
                        console.error('获取用户详情失败:', error);
                        alert('获取用户详情失败，请重试');
                    }
                },
                 
                async saveEditUser() {
                    try {
                        // 验证表单
                        if (!this.editUserForm.username || !this.editUserForm.full_name || !this.editUserForm.email) {
                            alert('请填写必填字段');
                            return;
                        }
                        
                        // 发送更新请求
                        const response = await axios.put(`/users/${this.editUserId}`, this.editUserForm);
                        
                        // 更新本地数据
                        const index = this.users.findIndex(u => u.id === this.editUserId);
                        if (index !== -1) {
                            this.users[index] = response.data;
                        }
                        
                        // 关闭模态框
                        this.showEditUserModal = false;
                        alert('用户更新成功');
                    } catch (error) {
                        console.error('更新用户失败:', error);
                        alert('更新用户失败，请重试');
                    }
                },
                 
                async deleteUser(id) {
                    if (!confirm('确定要删除这个用户吗？此操作不可撤销！')) {
                        return;
                    }
                    
                    try {
                        // 发送删除请求
                        await axios.delete(`/users/${id}`);
                        
                        // 更新本地数据
                        this.users = this.users.filter(u => u.id !== id);
                        alert('用户删除成功');
                    } catch (error) {
                        console.error('删除用户失败:', error);
                        alert('删除用户失败，请重试');
                    }
                },
                 
                async editDepartment(id) {
                    try {
                        // 获取部门详情
                        const response = await axios.get(`/departments/${id}`);
                        const department = response.data;
                        
                        // 填充编辑表单
                        this.editDepartmentId = department.id;
                        this.editDepartmentForm = {
                            name: department.name,
                            description: department.description
                        };
                        
                        // 显示编辑模态框
                        this.showEditDepartmentModal = true;
                    } catch (error) {
                        console.error('获取部门详情失败:', error);
                        alert('获取部门详情失败，请重试');
                    }
                },
                 
                async saveEditDepartment() {
                    try {
                        // 验证表单
                        if (!this.editDepartmentForm.name) {
                            alert('请填写部门名称');
                            return;
                        }
                        
                        // 发送更新请求
                        const response = await axios.put(`/departments/${this.editDepartmentId}`, this.editDepartmentForm);
                        
                        // 更新本地数据
                        const index = this.departments.findIndex(d => d.id === this.editDepartmentId);
                        if (index !== -1) {
                            this.departments[index] = response.data;
                        }
                        
                        // 关闭模态框
                        this.showEditDepartmentModal = false;
                        alert('部门更新成功');
                    } catch (error) {
                        console.error('更新部门失败:', error);
                        alert('更新部门失败，请重试');
                    }
                },
                 
                async deleteDepartment(id) {
                    if (!confirm('确定要删除这个部门吗？此操作不可撤销！')) {
                        return;
                    }
                    
                    try {
                        // 发送删除请求
                        await axios.delete(`/departments/${id}`);
                        
                        // 更新本地数据
                        this.departments = this.departments.filter(d => d.id !== id);
                        alert('部门删除成功');
                    } catch (error) {
                        console.error('删除部门失败:', error);
                        alert('删除部门失败，请重试');
                    }
                },
                 
                async editProject(id) {
                    try {
                        // 获取项目详情
                        const response = await axios.get(`/projects/${id}`);
                        const project = response.data;
                        
                        // 填充编辑表单
                        this.editProjectId = project.id;
                        this.editProjectForm = {
                            name: project.name,
                            description: project.description,
                            start_date: project.start_date.split('T')[0],
                            end_date: project.end_date ? project.end_date.split('T')[0] : '',
                            status: project.status,
                            manager_id: project.manager_id
                        };
                        
                        // 显示编辑模态框
                        this.showEditProjectModal = true;
                    } catch (error) {
                        console.error('获取项目详情失败:', error);
                        alert('获取项目详情失败，请重试');
                    }
                },
                 
                async saveEditProject() {
                    try {
                        // 验证表单
                        if (!this.editProjectForm.name || !this.editProjectForm.start_date) {
                            alert('请填写必填字段');
                            return;
                        }
                        
                        // 发送更新请求
                        const response = await axios.put(`/projects/${this.editProjectId}`, this.editProjectForm);
                        
                        // 更新本地数据
                        const index = this.projects.findIndex(p => p.id === this.editProjectId);
                        if (index !== -1) {
                            this.projects[index] = response.data;
                        }
                        
                        // 关闭模态框
                        this.showEditProjectModal = false;
                        alert('项目更新成功');
                    } catch (error) {
                        console.error('更新项目失败:', error);
                        alert('更新项目失败，请重试');
                    }
                },
                 
                async deleteProject(id) {
                    if (!confirm('确定要删除这个项目吗？此操作不可撤销！')) {
                        return;
                    }
                    
                    try {
                        // 发送删除请求
                        await axios.delete(`/projects/${id}`);
                        
                        // 更新本地数据
                        this.projects = this.projects.filter(p => p.id !== id);
                        alert('项目删除成功');
                    } catch (error) {
                        console.error('删除项目失败:', error);
                        alert('删除项目失败，请重试');
                    }
                },
                 
                async addUser() {
                    try {
                        // 简单验证
                        if (!this.newUser.full_name || !this.newUser.email || !this.newUser.department_id) {
                            alert('请填写必填字段');
                            return;
                        }
                         
                        // 创建新用户对象
                        const user = {
                            id: this.users.length + 1,
                            ...this.newUser,
                            created_at: new Date().toISOString().split('T')[0] // 当前日期
                        };
                         
                        // 添加到用户列表
                        this.users.push(user);
                         
                        // 更新部门的员工数量
                        const department = this.departments.find(d => d.id === parseInt(this.newUser.department_id));
                        if (department) {
                            department.employee_count = (department.employee_count || 0) + 1;
                        }
                         
                        // 重置表单并关闭模态框
                        this.resetNewUserForm();
                        this.showAddUser = false;
                         
                        // 更新图表
                        await this.initializeCharts();
                         
                        alert('用户添加成功');
                    } catch (error) {
                        console.error('添加用户失败:', error);
                        alert('添加用户失败，请重试');
                    }
                },
                 
                resetNewUserForm() {
                    this.newUser = { full_name: '', email: '', department_id: '', position: '' };
                },
                 
                async addDepartment() {
                    try {
                        // 简单验证
                        if (!this.newDepartment.name || !this.newDepartment.description) {
                            alert('请填写必填字段');
                            return;
                        }
                         
                        // 创建新部门对象
                        const department = {
                            id: this.departments.length + 1,
                            ...this.newDepartment,
                            employee_count: 0, // 新部门初始没有员工
                            created_at: new Date().toISOString().split('T')[0] // 当前日期
                        };
                         
                        // 添加到部门列表
                        this.departments.push(department);
                         
                        // 重置表单并关闭模态框
                        this.resetNewDepartmentForm();
                        this.showAddDepartment = false;
                         
                        // 更新图表
                        await this.initializeCharts();
                         
                        alert('部门添加成功');
                    } catch (error) {
                        console.error('添加部门失败:', error);
                        alert('添加部门失败，请重试');
                    }
                },
                 
                resetNewDepartmentForm() {
                    this.newDepartment = { name: '', description: '', manager_id: '' };
                },
                 
                async addProject() {
                    try {
                        // 简单验证
                        if (!this.newProject.name || !this.newProject.manager_name || !this.newProject.department_id) {
                            alert('请填写必填字段');
                            return;
                        }
                         
                        // 创建新项目对象
                        const project = {
                            id: this.projects.length + 1,
                            ...this.newProject,
                            start_date: new Date().toISOString().split('T')[0], // 当前日期
                            end_date: new Date(new Date().setMonth(new Date().getMonth() + 3)).toISOString().split('T')[0] // 默认三个月后
                        };
                         
                        // 添加到项目列表
                        this.projects.push(project);
                         
                        // 更新活跃项目数
                        if (project.status === 'in_progress') {
                            this.activeProjects += 1;
                        }
                         
                        // 重置表单并关闭模态框
                        this.resetNewProjectForm();
                        this.showAddProject = false;
                         
                        // 更新图表
                        await this.initializeCharts();
                         
                        alert('项目添加成功');
                    } catch (error) {
                        console.error('添加项目失败:', error);
                        alert('添加项目失败，请重试');
                    }
                },
                 
                resetNewProjectForm() {
                    this.newProject = { name: '', description: '', manager_name: '', department_id: '', budget: 0, progress: 0, status: 'planning' };
                },
                
                // 考勤相关方法
                async loadAttendanceData() {
                    try {
                        // 模拟API请求延迟
                        await new Promise(resolve => setTimeout(resolve, 500));
                        
                        // 如果没有考勤数据，生成模拟数据
                        if (this.attendanceRecords.length === 0) {
                            this.generateMockAttendanceData();
                        }
                        
                        // 初始化今日打卡状态
                        this.checkTodayAttendanceStatus();
                        
                        // 初始化日历
                        this.initializeCalendar();
                        
                        // 更新月度统计
                        this.updateMonthlyStats();
                        
                        // 初始化图表
                        await this.initializeAttendanceCharts();
                    } catch (error) {
                        console.error('加载考勤数据失败:', error);
                        this.generateMockAttendanceData();
                        this.checkTodayAttendanceStatus();
                        this.initializeCalendar();
                        this.updateMonthlyStats();
                        await this.initializeAttendanceCharts();
                    }
                },
                
                generateMockAttendanceData() {
                    const today = new Date();
                    const records = [];
                    const statuses = ['present', 'late', 'early', 'absent'];
                    const workDays = [0, 1, 2, 3, 4]; // 周一到周五
                    
                    // 生成最近30天的考勤数据
                    for (let i = 29; i >= 0; i--) {
                        const date = new Date(today);
                        date.setDate(date.getDate() - i);
                        const dayOfWeek = date.getDay();
                        
                        // 只生成工作日的考勤数据
                        if (workDays.includes(dayOfWeek)) {
                            const isToday = i === 0;
                            let status = statuses[Math.floor(Math.random() * 4)];
                            let checkInTime = null;
                            let checkOutTime = null;
                            let workDuration = null;
                            
                            // 工作日大概率是出勤状态
                            if (Math.random() > 0.15) {
                                status = 'present';
                                // 随机生成签到和签退时间
                                const checkInHour = 8 + Math.floor(Math.random() * 2) + Math.floor(Math.random() * 60) / 60;
                                const checkOutHour = 17 + Math.floor(Math.random() * 2) + Math.floor(Math.random() * 60) / 60;
                                
                                // 有20%的概率迟到
                                if (Math.random() < 0.2 && checkInHour > 9) {
                                    status = 'late';
                                }
                                
                                // 有15%的概率早退
                                if (Math.random() < 0.15 && checkOutHour < 18) {
                                    status = 'early';
                                }
                                
                                // 设置具体时间
                                checkInTime = new Date(date);
                                checkInTime.setHours(Math.floor(checkInHour), Math.floor((checkInHour - Math.floor(checkInHour)) * 60));
                                
                                checkOutTime = new Date(date);
                                checkOutTime.setHours(Math.floor(checkOutHour), Math.floor((checkOutHour - Math.floor(checkOutHour)) * 60));
                                
                                // 计算工作时长（小时）
                                const durationMs = checkOutTime - checkInTime;
                                workDuration = (durationMs / (1000 * 60 * 60)).toFixed(1);
                            } else {
                                status = 'absent';
                            }
                            
                            // 今日数据特殊处理（默认未打卡）
                            if (isToday) {
                                checkInTime = null;
                                checkOutTime = null;
                                workDuration = null;
                                status = 'absent';
                            }
                            
                            records.push({
                                id: records.length + 1,
                                date: date.toISOString().split('T')[0],
                                check_in_time: checkInTime,
                                check_out_time: checkOutTime,
                                work_duration: workDuration,
                                status: status
                            });
                        }
                    }
                    
                    this.attendanceRecords = records;
                    this.recentAttendanceRecords = records.slice(0, 5);
                },
                
                checkTodayAttendanceStatus() {
                    const today = new Date().toISOString().split('T')[0];
                    const todayRecord = this.attendanceRecords.find(record => record.date === today);
                    
                    if (todayRecord) {
                        this.isTodayCheckedIn = todayRecord.check_in_time !== null;
                        this.isTodayCheckedOut = todayRecord.check_out_time !== null;
                        this.todayCheckInTime = todayRecord.check_in_time;
                        this.todayCheckOutTime = todayRecord.check_out_time;
                    } else {
                        this.isTodayCheckedIn = false;
                        this.isTodayCheckedOut = false;
                        this.todayCheckInTime = null;
                        this.todayCheckOutTime = null;
                    }
                },
                
                async checkIn() {
                    try {
                        const now = new Date();
                        const today = now.toISOString().split('T')[0];
                        let todayRecord = this.attendanceRecords.find(record => record.date === today);
                        
                        if (!todayRecord) {
                            // 创建新记录
                            todayRecord = {
                                id: this.attendanceRecords.length + 1,
                                date: today,
                                check_in_time: now,
                                check_out_time: null,
                                work_duration: null,
                                status: 'present'
                            };
                            this.attendanceRecords.unshift(todayRecord);
                        } else {
                            // 更新现有记录
                            todayRecord.check_in_time = now;
                            todayRecord.status = 'present';
                        }
                        
                        // 更新状态
                        this.isTodayCheckedIn = true;
                        this.isTodayCheckedOut = false;
                        this.todayCheckInTime = now;
                        
                        // 更新日历
                        this.initializeCalendar();
                        
                        // 更新月度统计
                        this.updateMonthlyStats();
                        
                        // 更新图表
                        await this.updateAttendanceCharts();
                        
                        alert('签到成功！');
                    } catch (error) {
                        console.error('签到失败:', error);
                        alert('签到失败，请重试');
                    }
                },
                
                async checkOut() {
                    try {
                        const now = new Date();
                        const today = now.toISOString().split('T')[0];
                        const todayRecord = this.attendanceRecords.find(record => record.date === today);
                        
                        if (todayRecord && todayRecord.check_in_time) {
                            // 更新签退时间
                            todayRecord.check_out_time = now;
                            
                            // 计算工作时长（小时）
                            const durationMs = now - todayRecord.check_in_time;
                            todayRecord.work_duration = (durationMs / (1000 * 60 * 60)).toFixed(1);
                            
                            // 检查是否迟到或早退
                            const checkInHour = todayRecord.check_in_time.getHours() + todayRecord.check_in_time.getMinutes() / 60;
                            const checkOutHour = now.getHours() + now.getMinutes() / 60;
                            
                            if (checkInHour > 9) {
                                todayRecord.status = 'late';
                            }
                            if (checkOutHour < 18) {
                                todayRecord.status = todayRecord.status === 'late' ? 'late_early' : 'early';
                            }
                            
                            // 更新状态
                            this.isTodayCheckedOut = true;
                            this.todayCheckOutTime = now;
                            
                            // 更新日历
                            this.initializeCalendar();
                            
                            // 更新月度统计
                            this.updateMonthlyStats();
                            
                            // 更新图表
                            await this.updateAttendanceCharts();
                            
                            alert('签退成功！今日工作时长：' + todayRecord.work_duration + '小时');
                        } else {
                            alert('请先签到');
                        }
                    } catch (error) {
                        console.error('签退失败:', error);
                        alert('签退失败，请重试');
                    }
                },
                
                formatTime(date) {
                    if (!date) return '';
                    if (!(date instanceof Date)) {
                        date = new Date(date);
                    }
                    return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
                },
                
                initializeCalendar() {
                    const year = this.currentYear;
                    const month = this.currentMonth;
                    
                    // 设置月份显示名称
                    const monthNames = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'];
                    this.currentMonthDisplay = `${year}年${monthNames[month]}`;
                    
                    // 计算当月第一天是星期几
                    const firstDay = new Date(year, month, 1).getDay();
                    
                    // 计算当月有多少天
                    const daysInMonth = new Date(year, month + 1, 0).getDate();
                    
                    // 计算需要填充的空白单元格数量
                    this.emptyStartCells = Array.from({ length: firstDay }, (_, i) => i + 1);
                    
                    // 生成日历天数
                    const calendarDays = [];
                    const today = new Date();
                    const currentDate = today.getDate();
                    const currentMonth = today.getMonth();
                    const currentYear = today.getFullYear();
                    
                    for (let day = 1; day <= daysInMonth; day++) {
                        const date = new Date(year, month, day);
                        const dayOfWeek = date.getDay();
                        const dateStr = date.toISOString().split('T')[0];
                        const attendanceRecord = this.attendanceRecords.find(record => record.date === dateStr);
                        
                        calendarDays.push({
                            day: day,
                            isToday: day === currentDate && month === currentMonth && year === currentYear,
                            isWeekend: dayOfWeek === 0 || dayOfWeek === 6,
                            status: attendanceRecord ? attendanceRecord.status : null
                        });
                    }
                    
                    this.calendarDays = calendarDays;
                },
                
                previousMonth() {
                    this.currentMonth -= 1;
                    if (this.currentMonth < 0) {
                        this.currentMonth = 11;
                        this.currentYear -= 1;
                    }
                    this.initializeCalendar();
                },
                
                nextMonth() {
                    this.currentMonth += 1;
                    if (this.currentMonth > 11) {
                        this.currentMonth = 0;
                        this.currentYear += 1;
                    }
                    this.initializeCalendar();
                },
                
                updateMonthlyStats() {
                    const year = this.currentYear;
                    const month = this.currentMonth;
                    
                    // 过滤当月的考勤记录
                    const monthlyRecords = this.attendanceRecords.filter(record => {
                        const recordDate = new Date(record.date);
                        return recordDate.getFullYear() === year && recordDate.getMonth() === month;
                    });
                    
                    // 计算各类统计数据
                    const attendanceDays = monthlyRecords.filter(record => record.status === 'present' || record.status === 'late' || record.status === 'early' || record.status === 'late_early').length;
                    const lateCount = monthlyRecords.filter(record => record.status === 'late' || record.status === 'late_early').length;
                    const earlyLeaveCount = monthlyRecords.filter(record => record.status === 'early' || record.status === 'late_early').length;
                    const absentDays = monthlyRecords.filter(record => record.status === 'absent').length;
                    
                    // 模拟上月数据进行比较
                    const prevMonthAttendanceDays = attendanceDays - Math.floor(Math.random() * 5);
                    const prevMonthLateCount = lateCount - Math.floor(Math.random() * 3);
                    const prevMonthEarlyLeaveCount = earlyLeaveCount - Math.floor(Math.random() * 2);
                    const prevMonthAbsentDays = absentDays - Math.floor(Math.random() * 2);
                    
                    // 计算百分比变化
                    const percentageChange = this.getPercentageChange(prevMonthAttendanceDays, attendanceDays);
                    const latePercentageChange = this.getPercentageChange(prevMonthLateCount, lateCount);
                    const earlyLeavePercentageChange = this.getPercentageChange(prevMonthEarlyLeaveCount, earlyLeaveCount);
                    const absentPercentageChange = this.getPercentageChange(prevMonthAbsentDays, absentDays);
                    
                    // 更新统计数据
                    this.monthlyAttendanceStats = {
                        attendanceDays,
                        lateCount,
                        earlyLeaveCount,
                        absentDays,
                        percentageChange,
                        latePercentageChange,
                        earlyLeavePercentageChange,
                        absentPercentageChange
                    };
                },
                
                async initializeAttendanceCharts() {
                    // 确保考勤图表实例被销毁
                    if (this.attendanceTrendChartInstance) {
                        this.attendanceTrendChartInstance.destroy();
                        this.attendanceTrendChartInstance = null;
                    }
                    
                    if (this.attendanceTypeChartInstance) {
                        this.attendanceTypeChartInstance.destroy();
                        this.attendanceTypeChartInstance = null;
                    }
                    
                    // 等待DOM更新
                    await this.$nextTick();
                    
                    // 检查DOM元素是否存在
                    const trendChartCtx = this.$refs.attendanceTrendChart;
                    const typeChartCtx = this.$refs.attendanceTypeChart;
                    
                    if (trendChartCtx && typeChartCtx) {
                        // 初始化考勤趋势图表
                        this.initializeTrendChart(trendChartCtx);
                        
                        // 初始化考勤类型分布图表
                        this.initializeTypeChart(typeChartCtx);
                    }
                },
                
                initializeTrendChart(ctx) {
                    let labels = [];
                    let presentData = [];
                    let lateData = [];
                    let earlyData = [];
                    let absentData = [];
                    
                    const now = new Date();
                    
                    if (this.attendanceChartPeriod === 'week') {
                        // 本周数据
                        const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
                        for (let i = 6; i >= 0; i--) {
                            const date = new Date(now);
                            date.setDate(date.getDate() - i);
                            const dateStr = date.toISOString().split('T')[0];
                            const dayName = weekDays[date.getDay()];
                            const record = this.attendanceRecords.find(r => r.date === dateStr);
                            
                            labels.push(dayName);
                            presentData.push(record && (record.status === 'present' || record.status === 'late_early') ? 1 : 0);
                            lateData.push(record && (record.status === 'late' || record.status === 'late_early') ? 1 : 0);
                            earlyData.push(record && (record.status === 'early' || record.status === 'late_early') ? 1 : 0);
                            absentData.push(record && record.status === 'absent' ? 1 : 0);
                        }
                    } else if (this.attendanceChartPeriod === 'month') {
                        // 本月数据（按周分组）
                        const today = new Date();
                        const currentMonth = today.getMonth();
                        const currentYear = today.getFullYear();
                        const daysInMonth = new Date(currentYear, currentMonth + 1, 0).getDate();
                        
                        const weekData = Array(5).fill().map(() => ({
                            present: 0,
                            late: 0,
                            early: 0,
                            absent: 0
                        }));
                        
                        for (let day = 1; day <= daysInMonth; day++) {
                            const date = new Date(currentYear, currentMonth, day);
                            const dateStr = date.toISOString().split('T')[0];
                            const record = this.attendanceRecords.find(r => r.date === dateStr);
                            const weekIndex = Math.floor((day - 1) / 7);
                            
                            if (weekIndex < 5) {
                                if (record) {
                                    if (record.status === 'present') {
                                        weekData[weekIndex].present++;
                                    } else if (record.status === 'late') {
                                        weekData[weekIndex].late++;
                                    } else if (record.status === 'early') {
                                        weekData[weekIndex].early++;
                                    } else if (record.status === 'absent') {
                                        weekData[weekIndex].absent++;
                                    } else if (record.status === 'late_early') {
                                        weekData[weekIndex].late++;
                                        weekData[weekIndex].early++;
                                    }
                                }
                            }
                        }
                        
                        for (let i = 0; i < 4; i++) {
                            labels.push(`第${i + 1}周`);
                            presentData.push(weekData[i].present);
                            lateData.push(weekData[i].late);
                            earlyData.push(weekData[i].early);
                            absentData.push(weekData[i].absent);
                        }
                    } else if (this.attendanceChartPeriod === 'quarter') {
                        // 本季度数据（按月分组）
                        const today = new Date();
                        const currentQuarter = Math.floor(today.getMonth() / 3);
                        const currentYear = today.getFullYear();
                        
                        for (let i = 2; i >= 0; i--) {
                            const month = currentQuarter * 3 + i;
                            const monthNames = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'];
                            const monthData = this.attendanceRecords.filter(record => {
                                const recordDate = new Date(record.date);
                                return recordDate.getFullYear() === currentYear && recordDate.getMonth() === month;
                            });
                            
                            labels.push(monthNames[month]);
                            presentData.push(monthData.filter(r => r.status === 'present' || r.status === 'late_early').length);
                            lateData.push(monthData.filter(r => r.status === 'late' || r.status === 'late_early').length);
                            earlyData.push(monthData.filter(r => r.status === 'early' || r.status === 'late_early').length);
                            absentData.push(monthData.filter(r => r.status === 'absent').length);
                        }
                    }
                    
                    this.attendanceTrendChartInstance = new Chart(ctx, {
                        type: 'bar',
                        data: {
                            labels: labels,
                            datasets: [
                                {
                                    label: '出勤',
                                    data: presentData,
                                    backgroundColor: 'rgba(75, 192, 192, 0.7)',
                                    borderColor: 'rgba(75, 192, 192, 1)',
                                    borderWidth: 1
                                },
                                {
                                    label: '迟到',
                                    data: lateData,
                                    backgroundColor: 'rgba(255, 206, 86, 0.7)',
                                    borderColor: 'rgba(255, 206, 86, 1)',
                                    borderWidth: 1
                                },
                                {
                                    label: '早退',
                                    data: earlyData,
                                    backgroundColor: 'rgba(255, 159, 64, 0.7)',
                                    borderColor: 'rgba(255, 159, 64, 1)',
                                    borderWidth: 1
                                },
                                {
                                    label: '缺勤',
                                    data: absentData,
                                    backgroundColor: 'rgba(255, 99, 132, 0.7)',
                                    borderColor: 'rgba(255, 99, 132, 1)',
                                    borderWidth: 1
                                }
                            ]
                        },
                        options: {
                            responsive: true,
                            maintainAspectRatio: false,
                            scales: {
                                y: {
                                    beginAtZero: true,
                                    ticks: {
                                        precision: 0
                                    }
                                }
                            },
                            plugins: {
                                legend: {
                                    position: 'top'
                                }
                            }
                        }
                    });
                },
                
                initializeTypeChart(ctx) {
                    // 计算考勤类型分布
                    const presentCount = this.attendanceRecords.filter(record => record.status === 'present').length;
                    const lateCount = this.attendanceRecords.filter(record => record.status === 'late' || record.status === 'late_early').length;
                    const earlyCount = this.attendanceRecords.filter(record => record.status === 'early').length;
                    const absentCount = this.attendanceRecords.filter(record => record.status === 'absent').length;
                    
                    this.attendanceTypeChartInstance = new Chart(ctx, {
                        type: 'doughnut',
                        data: {
                            labels: ['出勤', '迟到', '早退', '缺勤'],
                            datasets: [{
                                data: [presentCount, lateCount, earlyCount, absentCount],
                                backgroundColor: [
                                    'rgba(75, 192, 192, 0.7)',
                                    'rgba(255, 206, 86, 0.7)',
                                    'rgba(255, 159, 64, 0.7)',
                                    'rgba(255, 99, 132, 0.7)'
                                ],
                                borderColor: [
                                    'rgba(75, 192, 192, 1)',
                                    'rgba(255, 206, 86, 1)',
                                    'rgba(255, 159, 64, 1)',
                                    'rgba(255, 99, 132, 1)'
                                ],
                                borderWidth: 1
                            }]
                        },
                        options: {
                            responsive: true,
                            maintainAspectRatio: false,
                            plugins: {
                                legend: {
                                    position: 'right'
                                },
                                tooltip: {
                                    callbacks: {
                                        label: function(context) {
                                            const total = context.dataset.data.reduce((a, b) => a + b, 0);
                                            const percentage = Math.round((context.raw / total) * 100);
                                            return context.label + ': ' + context.raw + ' (' + percentage + '%)';
                                        }
                                    }
                                }
                            }
                        }
                    });
                },
                
                async updateAttendanceCharts() {
                    await this.initializeAttendanceCharts();
                },
                
                // 计算百分比变化
                getPercentageChange(oldValue, newValue) {
                    if (oldValue === 0) {
                        return newValue > 0 ? 100 : 0;
                    }
                    return Math.round(((newValue - oldValue) / oldValue) * 100);
                }
            },
            
            // 监听视图变化，自动加载对应数据
            watch: {
                async currentView(newView) {
                    // 当切换到考勤管理视图时，加载考勤数据
                    if (newView === 'attendance') {
                        await this.loadAttendanceData();
                    }
                }
            },
            async mounted() {
                // 检查是否已登录
                const token = localStorage.getItem('token');
                if (token) {
                    this.isLoggedIn = true;
                    this.username = localStorage.getItem('username') || '';
                    
                    // 从localStorage恢复当前用户信息
                    const userStr = localStorage.getItem('currentUser');
                    if (userStr) {
                        try {
                            this.currentUser = JSON.parse(userStr);
                        } catch (e) {
                            console.error('Failed to parse currentUser from localStorage:', e);
                            this.currentUser = null;
                        }
                    }
                    
                    await this.loadAllData();
                }
            },
            // 在组件挂载时调用initApp方法
            mounted() {
                this.initApp();
            }
        });
         
        app.mount('#app');
    </script>
</body>
</html>